您的位置:首页 > 其它

boost::thread

2016-04-24 17:06 267 查看
使用无参函数创建线程

#include "stdafx.h"
#include <iostream>
#include <boost/thread.hpp>

void Foo()
{
std::cout << "Hello world, I'm a thread!" << std::endl;
}

int main(int argc, char* argv[])
{
//以下两种写法都可以
//boost::thread thrd(&Foo);
boost::thread thrd(Foo);
thrd.join();
return 0;
}

使用对象实例创建线程

#include "stdafx.h"
#include <iostream>
#include <boost/thread.hpp>

boost::mutex g_io_mutex;

class CTestClass
{
public:
CTestClass(int id) : m_id(id) {}

void operator()()
{
for(int i = 0; i < 10; ++i)
{
boost::mutex::scoped_lock lock(g_io_mutex);
std::cout<<m_id<<": "<<i<<std::endl;
}
}
private:
int m_id;
};

int main()
{
//创建一个临时对象
boost::thread thrd2(CTestClass(1));

CTestClass testClass_2( 2 );
//创建一个已有对象的引用
boost::thread thrd1(boost::ref( testClass_2 ));

thrd1.join();
thrd2.join();

system("pause");
return 0;
}

通过成员函数创建线程

#include "stdafx.h"
#include <iostream>
#include <boost/thread.hpp>

boost::mutex g_io_mutex;

class CTestClass
{
public:
CTestClass(int id) : m_id(id) {}

void operator()()
{
for(int i = 0; i < 10; ++i)
{
boost::mutex::scoped_lock lock(g_io_mutex);
std::cout<<m_id<<": "<<i<<std::endl;
}
}
void Foo()
{
std::cout << "Foo procedure." << std::endl;
}
private:
int m_id;
};

int main()
{
CTestClass testClass_1( 102 );
boost::function0<void> f = boost::bind(&CTestClass::Foo, &testClass_1);
boost::thread thrd1(f);
thrd1.join();

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: