BOOST库介绍(二)——BOOST多线程相关库

代码示例:

#include "stdafx.h"
#include<iostream>
#include<boost/thread.hpp>
#include<boost/bind.hpp>
#include<boost/date_time/posix_time/posix_time.hpp>
#include<list>
using namespace std;

class A
{
public:
	A(int x = 0) :m_i(x)
	{
		boost::thread thrd1=boost::thread(boost::bind(&A::inMsg, this, x));
		boost::thread thrd2 = boost::thread(boost::bind(&A::outMsg, this, x+1));
		thrd1.join();
		thrd2.join();
	}

	void inMsg(int i)
	{
		cout << "线程thread1的ID" << boost::this_thread::get_id() << endl;
		for (int i = 0; i < 1000; i++)
		{
			boost::mutex::scoped_lock lock(m_mutex);
			msgQueue.push_back(i);
			
		}
	}

	void outMsg(int i)
	{
		cout << "线程thread2的ID" << boost::this_thread::get_id() << endl;
		for (int i = 0; i < 1000; i++)
		{
			boost::mutex::scoped_lock lock(m_mutex);
			cout << "thread1 2=" << i << endl;
		}
	}
private:
	list<int> msgQueue;
	boost::mutex m_mutex;
	int m_i;
};

int _tmain(int argc, _TCHAR* argv[])
{
	A a(10);
	
	return 0;
}

代码解释:
bind()函数绑定器

boost::thread thrd1=boost::thread(boost::bind(&A::inMsg, this, x));
//创建线程,绑定函数;线程绑定需要类的成员函数,传递一个函数指针this

boost::mutex::scoped_lock
区域锁boost::mutex::scoped_lock,顾名思义就是在作用域内有效,当离开作用域自动释放锁。
scoped_lock类使用一个mutex参数来构造,并一直锁定这个mutex直到对象被销毁。如果这个正在被构造的mutex已经被别的线程锁定的话,当前线程就会进入wait状态,直到这个锁被解开。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值