互斥锁例子

/*
生产者执行完,消费者才执行。
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAXNITEMS 1000000
#define MAXNTHREADS 5

int nitems;

struct
{
	pthread_mutex_t mutex;//互斥锁
	int buff[MAXNITEMS];
	int nput;//下标
	int nval;//值
}shared = {PTHREAD_MUTEX_INITIALIZER};

void *produce(void* arg), *consume(void *arg);

int main(int argc, char *argv[])
{
	int i=0, nthreads = 0, count[MAXNITEMS];
	pthread_t tid_produce[MAXNTHREADS], tid_consume;

	nthreads= 5;
	nitems = MAXNITEMS;

	for(i=0; i < nthreads; i++ )
	{
		count[i] = 0;
		pthread_create(&tid_produce[i], NULL, produce, &count[i]);
	}
	for(i=0; i < nthreads; i++)
	{
		pthread_join(tid_produce[i],NULL);
		printf("count[%d] = %d\n", i, count[i]);
	}
	pthread_create(&tid_consume, NULL, consume, NULL);
	pthread_join(tid_consume, NULL);
	exit(0);
}

//生产者有序的 对数组进行元素进行操作
void *produce(void *arg)
{
	for( ; ; )
	{
		pthread_mutex_lock(&shared.mutex);
		if(shared.nput >= nitems)
		{
			pthread_mutex_unlock(&shared.mutex);
			return NULL;
		}
		shared.buff[shared.nput] = shared.nval;
		shared.nput++;
		shared.nval++;
		pthread_mutex_unlock(&shared.mutex);
		*((int*)arg) +=1;//每个线程处理的次数加1
	}
}

//消费者线程只是验证数组是否正确
void *consume(void *arg)
{
	int i = 0;
	for(i = 0; i < nitems; i++)
	{
		if(shared.buff[i] != i)
		{
			printf("buff[%d] = %d\n", i, shared.buff[i]);
		}
	}
	return NULL;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值