linux 多线程(条件变量)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
/**
*int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t * cond_attr);
*int pthread_cond_signal(pthread_cond_t *cond);
*int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t * mutex);
*int pthread_cond_broadcast(pthread_cond_t *cond);
*int pthread_cond_timewait(pthread_cond_t *cond, pthread_mutex_t * mutex, const struct timespec * abstime);
*int pthread_cond_destroy(pthread_cond_t *cond);
*/

void * pthread_odd_function(void * arg);
void * pthread_even_function(void * arg);
pthread_mutex_t work_mutex;
pthread_cond_t work_cond;

#define MAX_COUNT 10
int count = 0;

int main(int argc, char const *argv[])
{
	pthread_t pthread_odd;
	pthread_t pthread_even;
	pthread_attr_t pthread_attr;
//	void * result;
	int res;

	res = pthread_attr_init(&pthread_attr);//init pthread attribute,step 1
	if (res != 0)
	{
		perror("pthread_attr_init failed!");
		exit(EXIT_FAILURE);
	}

	res = pthread_cond_init(&work_cond,NULL);
	if (res != 0)
	{
		perror("pthread_cond_init failed!");
		exit(EXIT_FAILURE);
	}

	res = pthread_mutex_init(&work_mutex,NULL);
	if (res != 0)
	{
		perror("pthread_mutex_init failed!");
		exit(EXIT_FAILURE);
	}

	pthread_attr_setdetachstate(&pthread_attr,PTHREAD_CREATE_DETACHED);//design pthread attribute step 2

	res = pthread_create(&pthread_odd,&pthread_attr,pthread_odd_function,NULL);//step 3
	if (res != 0)
	{
		perror("pthread_create failed!");
		exit(EXIT_FAILURE);	
	}

	res = pthread_create(&pthread_even,&pthread_attr,pthread_even_function,NULL);
	if (res != 0)
	{
		perror("pthread_create failed!");
		exit(EXIT_FAILURE);	
	}

	while(count < MAX_COUNT);//wait the two sons threads finished 
	pthread_mutex_destroy(&work_mutex);
	pthread_cond_destroy(&work_cond);
	pthread_exit(NULL);
	return 0;
}

void * pthread_odd_function(void *arg)//step 4
{
	pthread_mutex_lock(&work_mutex);
	while(count < MAX_COUNT)
	{
		if (count % 2 == 1)
		{
			++count;
			printf("the odd count is : %d\n", count);
			pthread_cond_signal(&work_cond);//in order to release the thread of even
		}
		else
			pthread_cond_wait(&work_cond,&work_mutex);//the pthread is blocked,wait for the condition
	}
	pthread_mutex_unlock(&work_mutex);
}


void * pthread_even_function(void *arg)//step 5
{
	pthread_mutex_lock(&work_mutex);
	while(count < MAX_COUNT)
	{
		if (count % 2 == 0)
		{
			++count;
			printf("the even count is : %d\n", count);
			pthread_cond_signal(&work_cond);//in order to release the thread of odd
		}
		else
			pthread_cond_wait(&work_cond,&work_mutex);//wait the condition satisfied
	}
	pthread_mutex_unlock(&work_mutex);
}


mutex是为了控制线程共享临界资源count,cond是为了在线程不满足条件的情况下,触发另一个线程,防止死锁

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值