linux c线程间通信之条件变量

条件变量是和互斥量一起使用的。
以下演示了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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值