boost::thread
1、boost::thread类就代表一个可执行的线程。缺省构造函数创建一个代表当前执行线程的实例。
#include <boost/thread/thread.hpp> #include <iostream> #include <thread> // std::thread, std::thread::id, std::this_thread::get_id #include <chrono> // std::chrono::seconds void hello() { std::cout << "Hello world, I'm a thread!" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); } int main(int argc, char* argv[]) { boost::thread thrd(&hello); thrd.join(); return 0; }
2、在类内部创建线程
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; }
3、绑定函数对象
#include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/bind.hpp> #include <iostream> boost::mutex io_mutex; void count(int id) { for (int i = 0; i < 10; ++i) { boost::mutex::scoped_lock lock(io_mutex); std::cout << id << ": " << i << std::endl; } } int main(int argc, char* argv[]) { boost::thread thrd1(boost::bind(&count, 1)); boost::thread thrd2(boost::bind(&count, 2)); thrd1.join(); thrd2.join(); return 0; }
4、如果要求start()和hello()方法不能是静态方法则采用下面的方法创建线程:
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::thread thrd( f ); thrd.join(); } }; int main(int argc, char* argv[]) { HelloWorld hello; hello.start(); return 0; }
5、用类内部函数在类外部创建线程
class HelloWorld { public: void hello(const std::string& str) { std::cout < } }; 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; }
6、每个线程都处理属于自己的数据实例,尽管它们都是使用同一个boost::thread_specific_ptr。
#include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/tss.hpp> #include <iostream> boost::mutex io_mutex; boost::thread_specific_ptr<int> ptr; struct count { count(int id) : id(id) { } void operator()() { if(ptr.get() == 0) ptr.reset(new int(0)); for (int i = 0; i < 10; ++i) { (*ptr)++; boost::mutex::scoped_lock lock(io_mutex); std::cout << id << ": " << *ptr << 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; }
7、boost::call_once的例子。其中定义了一个静态的全局整数,初始值为0;还有一个由BOOST_ONCE_INIT初始化的静态boost::once_flag实例。
只被执行了一次。
#include <boost/thread/thread.hpp> #include <boost/thread/once.hpp> #include <iostream> int i = 0; boost::once_flag flag = BOOST_ONCE_INIT; void init() { ++i; } void thread() { boost::call_once(&init, flag); } int main(int argc, char* argv[]) { boost::thread thrd1(&thread); boost::thread thrd2(&thread); thrd1.join(); thrd2.join(); std::cout << i << std::endl; return 0; }