直接上代码,主要用到sem_trywait & sem_post

复制代码
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<semaphore.h>
#include<time.h>

sem_t sem_cal;
sem_t sem_times;

typedef struct _cal_
{
    int sum;
}CAL;
CAL cal;


void *calculate(void*arg)
{
    int i;
    int sum;
    for(i = 0; i < 3; i++)
    {
        cal.sum = cal.sum + i;
        sleep(1);
    }
    sem_post(&sem_cal);
}

void *sum(void *arg)
{
    sem_wait(&sem_cal);
    printf("the sum is %d\n",cal.sum);
    sem_post(&sem_times);
}

void do_other()
{
    printf("do others\n");
}

void *times(void *arg)
{
    //do others
    while(1)
    {
        if(!sem_trywait(&sem_times))
        {
            printf("the times is %d\n",cal.sum * cal.sum);
            break;
        }
        do_other();
        sleep(1);
    }
}

int main(void)
{
    int ret=-1;
    pthread_t th[3];
    sem_init(&sem_cal,0,0);
    sem_init(&sem_times,0,0);
    ret = pthread_create(&th[0],NULL,calculate,NULL);
    if (ret != 0)
    {
        printf("Pthread_create failed\n");
        return -1;
    }                    

    ret = pthread_create(&th[1],NULL,sum,NULL);
    if (ret != 0)
    {
        printf("Pthread_create failed\n");
        return -1;
    }                    

    ret = pthread_create(&th[2],NULL,times,NULL);
    if (ret != 0)
    {
        printf("Pthread_create failed\n");
        return -1;
    }                    


    pthread_join(th[0],NULL);
    pthread_join(th[1],NULL);
    pthread_join(th[2],NULL);
    return 0;
}
View Code
复制代码

 pthread1

|----------------|post1|

 pthread2

|----------------|wait1|---------------|post|

 pthread2

|----------------|wait2|-----do_others---|

 

do_others 可以在pthread2 post 前执行业务。