linux c编程——信号量

信号量

信号量是进化版的互斥量,允许多个线程访问共享资源

例子

#include 
#include 
#include 
#include 

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int beginnum = 1000;

typedef struct _ProdInfo{
    int num;
    struct _ProdInfo *next;
}ProdInfo;

ProdInfo *Head = NULL;

void *thr_producter(void *arg){
    //负责在链表添加数据
    while (1)
    {
        ProdInfo * prod = malloc(sizeof(ProdInfo));
        prod->num = beginnum++;
        printf("----%s----self=%lu----%d\n",__FUNCTION__,pthread_self(),prod->num);
        pthread_mutex_lock(&mutex);
        //add to list
        prod->next = Head;
        Head = prod;
        pthread_mutex_unlock(&mutex);
        //发起通知
        pthread_cond_signal(&cond);
        sleep(rand()%4);
    }
    return NULL;
}

void *thr_customer(void *arg){
    ProdInfo * prod = NULL;
    while (1)
    {
        //取链表的数据
        pthread_mutex_lock(&mutex);
        while(Head == NULL){
            pthread_cond_wait(&cond,&mutex);//在此之前必须先加锁
        }
        prod = Head;
        Head = Head->next;
        printf("----%s----self=%lu----%d\n",__FUNCTION__,pthread_self(),prod->num);
        pthread_mutex_unlock(&mutex);
        sleep(rand()%4);
        free(prod);
    }
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t tid[2];
    pthread_create(&tid[0],NULL,thr_producter,NULL);
    pthread_create(&tid[1],NULL,thr_customer,NULL);
    pthread_create(&tid[2],NULL,thr_customer,NULL);

    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
    pthread_join(tid[2],NULL);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}

输出

----thr_producter----self--140546015598336----num---100
----thr_customer----self--140546007205632----num---100
----thr_producter----self--140546015598336----num---101
----thr_customer----self--140546007205632----num---101
----thr_producter----self--140546015598336----num---102
----thr_customer----self--140546007205632----num---102
----thr_producter----self--140546015598336----num---103
----thr_customer----self--140546007205632----num---103
----thr_producter----self--140546015598336----num---104
----thr_customer----self--140546007205632----num---104
----thr_producter----self--140546015598336----num---105
----thr_customer----self--140546007205632----num---105
----thr_producter----self--140546015598336----num---106
----thr_customer----self--140546007205632----num---106

你可能感兴趣的:(Deepin,linux)