条件变量是和互斥量一起使用的。
以下演示了2个线程,其中一个线程把一个变量修改为1,然后等待另外一个线程把这个变量修改为0,然后再重复以上动作。
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <assert.h>
#include <semaphore.h>
/**
* https://linux.die.net/man/3/pthread_cond_wait
*
*/
static pthread_mutex_t mutex;
static int key = 0;
// Declaration of thread condition variable
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
void* calls(void *ptr) {
int flag = 0;
pthread_mutex_lock(&mutex);
if (key == 1) {
key = 0;
pthread_cond_broadcast(&cond1);
}
while (1) {
pthread_cond_wait(&cond1, &mutex);
printf("1 after wait,key is : %d\n", key);
if (key == 1) {
key = 0;
pthread_cond_broadcast(&cond1);
}
}
return NULL;
}
void* calls2(void *ptr) {
int flag = 0;
pthread_mutex_lock(&mutex);
if (key == 0) {
key = 1;
pthread_cond_broadcast(&cond1);
}
while (1) {
pthread_cond_wait(&cond1, &mutex);
printf("2 after wait,key is : %d\n", key);
if (key == 0) {
key = 1;
pthread_cond_broadcast(&cond1);
}
}
printf("thread2: exit \n");
return NULL;
}
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_t thread;
pthread_t thread2;
pthread_create(&thread, NULL, calls, NULL);
sleep(1);
pthread_create(&thread2, NULL, calls2, NULL);
sleep(1);
pthread_join(thread, NULL);
pthread_join(thread2, NULL);
if (0 != pthread_mutex_destroy(&mutex)) {
perror("pthread_mutex_destroy");
}
if (pthread_cond_destroy(&cond1) != 0) {
perror("pthread_cond_destroy() error");
exit(2);
}
printf("main exit\n");
return EXIT_SUCCESS;
}