线程同步----条件变量的使用

.

条件变量:本身不是锁,但可以造成线程阻塞,通常与互斥锁配合使用;

主要应用函数: (1)pthread_cond_init
* (2)pthread_cond_wait (&cond,&mutex);
三个作用:1. 阻塞等待cond条件变量被唤醒;
2. 阻塞等待时,同时释放互斥锁;(1,2两部为一个原子操作)
3. 当被唤醒时,wait返回解除阻塞并且重新获取锁pthread_mutex_lock();
(3)pthread_cond_timewait
(4)pthread_cond_signal
(5)pthread_cond_broadcast
(6)pthread_cond_destroy

生产者------消费者模型的实现
在这里插入图片描述代码实现

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<time.h>
typedef struct Node{
        int num;
        struct Node * next;
}Node;

pthread_mutex_t mutex =PTHREAD_MUTEX_INITIALIZER;
Node * head=NULL;
Node * mp=NULL;
void *product(void * arg)
        {
                mp=(struct Node*)malloc(sizeof(struct Node));//生产
                mp->num = rand()%100;
                printf("----------------product %d\n",mp->num);

                pthread_mutex_lock(&mutex);//插入临界资源
                mp->next=head;
                head=mp;
                pthread_mutex_unlock(&mutex);

                pthread_cond_signal(&has_producted);
                sleep(rand()%3);
        }
}
void *consume(void *arg)
{
        while(1)
        {
                pthread_mutex_lock(&mutex);
                while(head==NULL)
                {
                }
                Node* p= head->next;
                printf("-------------------------consume %d\n",head->num);
                free(head);
                head=p;

                pthread_mutex_unlock(&mutex);
                sleep(1);
        }
}


int main()
{
        srand(time(NULL));
        pthread_t ptid,ctid;

        pthread_create(&ptid,NULL, product,NULL);
        pthread_create(&ctid,NULL,consume,NULL);


        pthread_join(ptid,NULL);
        pthread_join(ctid,NULL);

        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&has_producted);
        return 0;
}

发布了52 篇原创文章 · 获赞 14 · 访问量 5606

猜你喜欢

转载自blog.csdn.net/YanWenCheng_/article/details/104085491