pthread_cond_wait

前要先加锁
pthread_cond_wait内部会解锁,然后等待条件变量被其它线程激活
pthread_cond_wait被激活后会再自动加锁
激活线程:
加锁(和等待线程用同一个锁)
pthread_cond_signal发送信号
解锁

线程便会调用pthread_cond_wait阻塞自己,但是它持有的锁怎么办呢,如果他不归还操作系统,那么其他线程将会无法访问公有资源。这就要追究一下pthread_cond_wait的内部实现机制,当pthread_cond_wait被调用线程阻塞的时候,pthread_cond_wait会自动释放互斥锁。释放互斥锁的时机是什么呢:是线程从调用pthread_cond_wait到操作系统把他放在线程等待队列之后

#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int count = 0;

void* decrement(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (count == 0)
pthread_cond_wait(&cond, &mutex);
count--;
printf("消费一%d\n", count);
pthread_mutex_unlock(&mutex);
sleep(7);
}

return NULL;
}

void* decrement1(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (count == 0)
pthread_cond_wait(&cond, &mutex);
count--;
printf("消费二%d\n", count);
pthread_mutex_unlock(&mutex);
sleep(5);
}
return NULL;
}
void* increment(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
count++;
printf("生产%d\n", count);
if (count != 0)
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(2);
}
return NULL;
}

int main(int argc, char* argv[]) {
pthread_t tid_in, tid_de, tid_de1;
pthread_create(&tid_de, NULL, (void*)decrement, NULL);
pthread_create(&tid_in, NULL, (void*)increment, NULL);
pthread_create(&tid_de1, NULL, (void*)decrement1, NULL);
while (1);
pthread_join(tid_de, NULL);
pthread_join(tid_in, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}

posted @ 2021-07-22 16:23  MoonXu  阅读(242)  评论(0编辑  收藏  举报