最近因爲任務需要,需要讓一個類的函數作爲線程執行,查詢很多方法後發現自己方向一開始就錯了,不應該用系統函數,而是用boost庫,這裏就簡單介紹一下如何使用boost庫讓類函數作爲線程執行。
boost::thread有兩個構造函數:
(1)thread():構造一個表示當前執行線程的線程對象;
(2)explicit thread(const boost::function0& threadfunc):
boost::function0可以簡單看爲:一個無返回(返回void),無參數的函數。這裏的函數也可以是類重載operator()構成的函數;該構造函數傳入的是函數對象而並非是函數指針,這樣一個具有一般函數特性的類也能作爲參數傳入,在下面有例子。
- 類重載operator()構成的函數創建線程
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <iostream>
boost::mutex io_mutex;
struct count
{
count(int id) : id(id) { }
void operator()()
{
for (int i = 0; i < 10; ++i)
{
boost::mutex::scoped_lock
lock(io_mutex);
std::cout << id << ": "
<< i << std::endl;
}
}
int id;
};
int main(int argc, char* argv[])
{
boost::thread thrd1(count(1));
boost::thread thrd2(count(2));
thrd1.join();
thrd2.join();
return 0;
}
- 在類內部對static函數創建線程
#include <boost/thread/thread.hpp>
#include <iostream>
class HelloWorld
{
public:
static void hello()
{
std::cout <<
"Hello world, I''m a thread!"
<< std::endl;
}
static void start()
{
boost::thread thrd( hello );
thrd.join();
}
};
int main(int argc, char* argv[])
{
HelloWorld::start();
return 0;
}
在這裏start()和hello()方法都必須是static方法。
- 使用boost::bind函數創建線程
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <iostream>
class HelloWorld
{
public:
void hello()
{
std::cout <<
"Hello world, I''m a thread!"
<< std::endl;
}
void start()
{
boost::function0< void> f = boost::bind(&HelloWorld::hello,this);
//或boost::function<void()> f = boost::bind(&HelloWorld::hello,this);
boost::thread thrd( f );
thrd.join();
}
};
int main(int argc, char* argv[])
{
HelloWorld hello;
hello.start();
return 0;
}
- 在Singleton模式內部創建線程
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <iostream>
class HelloWorld
{
public:
void hello()
{
std::cout <<
"Hello world, I''m a thread!"
<< std::endl;
}
static void start()
{
boost::thread thrd( boost::bind
(&HelloWorld::hello,&HelloWorld::getInstance() ) ) ;
thrd.join();
}
static HelloWorld& getInstance()
{
if ( !instance )
instance = new HelloWorld;
return *instance;
}
private:
HelloWorld(){}
static HelloWorld* instance;
};
HelloWorld* HelloWorld::instance = 0;
int main(int argc, char* argv[])
{
HelloWorld::start();
return 0;
}
- 在類外用類內部函數創建線程
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <string>
#include <iostream>
class HelloWorld
{
public:
void hello(const std::string& str)
{
std::cout <<str<< std::endl;
}
};
int main(int argc, char* argv[])
{
HelloWorld obj;
boost::thread thrd( boost::bind(&HelloWorld::hello,&obj,"Hello
world, I''m a thread!" ) ) ;
thrd.join();
return 0;
}
原文鏈接:https://blog.csdn.net/jack_20/article/details/79892250