【学习总结】多线程编程


  • 线程互斥pthread_mutex_t

线程间除堆栈不同之外,代码区和数据段都在一个空间中。如果不进行控制会造成数据混乱,简单的使用pthread_mutex_t实现线程互斥的测试

//thread_lock.c
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

static int value =0;
pthread_mutex_t mutex;          //控制线程互斥,否则会造成pthread1和2同时对value变量进行操作造成混乱


void *func()
{
	while( value < 10 )
	{
		//sleep(5);
		//printf("pthread:%ld,")
		pthread_mutex_lock(&mutex);
		printf("mutex:%ld\n",mutex);
		printf("phread:%ld begin\n",pthread_self());
		value++;
		sleep(5);
		printf("phread:%ld,value=%d\n",pthread_self(),value);
		printf("pthread:%ld end\n",pthread_self());
		pthread_mutex_unlock(&mutex);
		sleep(1);         //当前的线程释放代码段,阻塞的线程获取到代码段并执行
	}

}

int main()
{
	pthread_t pthread1,pthread2;
	
	if(pthread_create(&pthread1,NULL,func,NULL))
	{
		return -1;
	}
	sleep(1);
	if(pthread_create(&pthread2,NULL,func,NULL))
	{
		return -1;
	}
	pthread_join( pthread1 , NULL);
	pthread_join( pthread2 , NULL);	
//	while(1)
//		sleep(0);
	return 0;
}

gcc thread_lock.c -o thread_lock -lpthread


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值