代码示例:
#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状态,直到这个锁被解开。
。