C++-BOOST(1)-线程(Thread)与互斥量(mutex)

1.线程调用两种方式:函数与类

using namespace boost;
//1.函数调用
//2.类调用
void fun()
{
	cout << "fun Hello world, I''m a fun thread!" << endl;
}
class myClassThread
{
  public:
	void fun()    //被调用的函数
	{
		cout <<	"Hello world, I''m a myClassThread!"<<endl;
	}
	void start()  //启动线程函数
	{
		boost::function0< void> f = boost::bind(&myClassThread::fun, this);
		boost::thread thrd(f);
		thrd.join();
	}

};

void myThread_main()
{
	cout << "myThread_main" << endl;
	
	boost::thread thrd(&fun);   //1.调用函数线程
	thrd.join();

	cout << " myClassThread" << endl;//2.调用类线程
	myClassThread m_thread;
	m_thread.start();
}


2.互斥量:2.1mutex  会阻塞线程 单独用时要try catch
                  2.2timed_mutex 超时立即返回
                  2.3 lock_guard 自动完成mutex锁定解锁操作
 

void myThread_main()
{
	
	//互斥变量,
	//1.1 mutex 但是会阻塞线程 单独用时要try catch
	boost::mutex mu;   
	try {
		mu.lock();                  //锁定互斥量
		cout<<"操作共享资源"<<endl; //操作共享资源
		mu.unlock();                //解锁互斥量

	}
	catch (...)
	{
		mu.unlock();
	}

	//1.2 timed_mutex 超时立即返回
	boost::timed_mutex tmu;
	auto flag = tmu.try_lock_for(100_ms);//等待100ms
	if (flag)
	{
		cout<<"lock timed_mutex"<<endl;//访问共享资源
		tmu.unlock();
	}
	//哪怕未获得解锁,也执行其他操作

	 //1.3 lock_guard 自动完成mutex锁定解锁操作
	 //1.3.1 与mutex同用
	boost::mutex mu2;                         //声明互斥量对象
	boost::lock_guard<boost::mutex> g(mu2);   //使用lock_guard
	cout<<"some operation"<<endl;             //访问共享资源


	//3.3.2 与timed_mutex同用
	boost::timed_mutex tmu2;                  //定义互斥量
	auto flag = tmu2.try_lock_for(100_ms);     //锁定时间为100ms
	if (flag)
	{
	                    //定义互斥量
		boost::lock_guard< boost::timed_mutex> g(tmu2, boost::adopt_lock);//不会再次加锁
		cout << "lock timed_mutex" << endl;                             //访问共享资源
		
	}
	                                                  //自动释放




}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值