条件变量

    xiaoxiao2022-06-30  96

    条件变量是一种逻辑稍微复杂一点的同步互斥机制,条件变量必须跟互斥锁一起配合使用。 使用步骤:

    1、条件变量相关API函数 注意:根其他的同步互斥机制一样,使用前要初始化,参数attr一般设置为NULL。当使用pthread_cond_destroy()销毁一个条件变量之后,他的值变得不确定,再使用必须重新初始化。

    注意:pthread_cond_broadcast()用来唤醒全部的等待线程,pthread_cond_signal()只是换新一个等待线程。

    2、例子 2.1.定义一个条件变量pthread_cond_t 2.2.初始化条件变量pthread_cond_init() 2.3.使用条件变量pthread_cond_broadcast()/pthread_cond_signal() 2.4.销毁条件变量pthread_cond_desttoy()

    #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/shm.h> #include <pthread.h> #include <semaphore.h> int balance = 0; pthread_mutex_t m; pthread_cond_t v; void *TimeCount(void *atg) { static int count = 0; while(1) { sleep(1); printf("time:%d\n", count++); } } void *Routine(void *arg) { pthread_mutex_lock(&m); //加锁,取钱 printf("wait before tid:%d \n", (int)arg); while(balance < 100) pthread_cond_wait(&v, &m); //进入等待睡眠,同时解锁了互斥锁m,等待pthread_cond_broadcast()或者pthread_cond_signal()函数唤醒 printf("wait after tid:%d, balance:%d\n", (int)arg, balance); balance -= 100; pthread_mutex_unlock(&m); //解锁 pthread_exit("routine exit"); //正常退出,并返回"routine exit" } int main(int argc, void *argv[]) { if(argc != 2) { printf("please input pthreadNum\n"); return -1; } pthread_mutex_init(&m, NULL); pthread_cond_init(&v, NULL); pthread_t time; pthread_create(&time, NULL, TimeCount, NULL); int i, timeNum = atoi(argv[1]); pthread_t tid; for(i=0; i<timeNum; i++) { pthread_create(&tid, NULL, Routine, (void *)i ); } sleep(3); pthread_mutex_lock(&m); //加锁,在加钱即加balance sleep(3); balance += (timeNum - 3) * 100 ; pthread_cond_broadcast(&v); //通知所有阻塞在条件变量里的等待线程(唤醒) pthread_mutex_unlock(&m); //加钱后,解锁 pthread_exit(NULL); }

    最新回复(0)