#include <head.h>
//定义条件变量
pthread_cond_t cond;
pthread_mutex_t mutex;
int date = 0;
//生产者线程
void* task1(void* arg)
{
while (1) {
date++;
if (date == 10) {
printf("hello ");
pthread_cond_signal(&cond);
}
}
}
//消费者线程
void* task2(void* arg)
{
while (1) {
pthread_cond_wait(&cond, &mutex);
printf("world\n");
date = 0;
}
}
int main(int argc, const char* argv[])
{
pthread_t tid1, tid2;
// 2初始化条件变量
pthread_cond_init(&cond, NULL);
if ((errno = pthread_create(&tid1, NULL, task1, NULL)) != 0)
PRINT_ERR("create thread1 error");
if ((errno = pthread_create(&tid2, NULL, task2, NULL)) != 0)
PRINT_ERR("create thread1 error");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
// 3.销毁条件变量
pthread_cond_destroy(&cond);
return 0;
}
使用条件变量实现两个线程的同步(不使用延时sleep)
最新推荐文章于 2024-01-06 15:26:36 发布