用c++简单的封装线程c中互斥锁

#include <iostream>
#include <pthread.h>
#include <stdio.h>


//用c++简单的封装互斥锁
class LOCK
{
	private:
		pthread_mutex_t mutex;
	public:
		LOCK();
		virtual ~LOCK();
		
		void lock_t();
		void unlock_t();
		void trylock_t();
};

LOCK::LOCK()
{
	pthread_mutex_init(&mutex, NULL);   //在构造函数中直接初始化互斥锁
}

LOCK::~LOCK()
{

}
void LOCK::lock_t()
{
	pthread_mutex_lock(&mutex);
}
void LOCK::unlock_t()
{
	pthread_mutex_unlock(&mutex);
}
void LOCK::trylock_t()
{
	pthread_mutex_trylock(&mutex);
}


//全局变量
int a = 0;
//创建锁对象
LOCK lock;

//线程回调函数
void * thread1(void * arg)
{
	while(1)
	{
		printf("I am thread1\n");
		lock.lock_t();
		a++;
		printf("thread1-a === %d\n",a);
		lock.unlock_t();
		sleep(1);
	}
}

void * thread2(void *arg)
{
	while(1)
	{
		printf("I am thread2\n");
		lock.lock_t();
		a++;
		printf("thread2-a === %d\n",a);
		lock.unlock_t();
		sleep(2);
	}
}
int main(int argc,char * argv[])
{
	//创建两个线程
	pthread_t test1;
    pthread_t test2;
	

	pthread_create(&test1,NULL,thread1,NULL);
	pthread_create(&test2,NULL,thread2,NULL);
	
	pthread_join(test1,NULL);
	pthread_join(test2,NULL);
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值