boost::thread编程-线程创建

boost::thread库提供了以下三种线程启动方式:

1)、最简单的方式

// BoostThread.cpp : 定义控制台应用程序的入口点。
//

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

void thread_fun(std::string s)
{
	std::cout<<"thread parameter:"<<s<<std::endl;
	std::cout<<"I am a thread!!!"<<std::endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	boost::thread thrd(thread_fun,"hello");
	thrd.join();
	getchar();
	return 0;
}
2)、用struct结构operator成员函数来启动

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

struct callable
{
	callable(std::string parameter):parameter(parameter){}
	void operator()()
	{
		std::cout<<"thread parameter:"<<parameter<<std::endl;
		std::cout<<"I am a thread!!!"<<std::endl;
	}
	std::string parameter;
};

int _tmain(int argc, _TCHAR* argv[])
{
	boost::thread thrd1(callable("hello1"));
	boost::thread thrd2(callable("hello2"));
	thrd1.join();
	thrd2.join();
	getchar();
	return 0;
}

3)、以成员函数方式启动线程

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

class ThreadClass
{
public:
	void fun(const std::string ¶meter)
	{
		std::cout<<"thread parameter:"<<parameter<<std::endl;
		std::cout<<"I am a thread!!!"<<std::endl;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	ThreadClass obj;
	boost::thread thrd1(boost::bind(&ThreadClass::fun,&obj,"hello1"));
	boost::thread thrd2(boost::bind(&ThreadClass::fun,&obj,"hello2"));
	thrd1.join();
	thrd2.join();
	getchar();
	return 0;
}


你可能感兴趣的:(boost::thread编程-线程创建)