1.线程管理
最重要的一个类是boost::thread,是在boost/thread.hpp里定义的,用来创建一个新线程。
#include <boost/thread.hpp> #include <iostream> void wait(int seconds) { boost::this_thread::sleep(boost::posix_time::seconds(seconds)); } void thread() { for (int i = 0; i < 5; ++i) { wait(1); std::cout << i << std::endl; } } int main() { boost::thread t(thread); t.join(); return 0; }
上述执行函数的名称被传递到boost::thread的构造函数,一旦变量t被创建,该thread()函数在其所在线程中被立即执行。join()方法是一个阻塞调用:可以暂停当前线程,直到调用join()的线程结束与你想那个。这会使得main()函数一直会等待到thread()运行结束。
一个特定的线程可以通过thread变量访问,通过这个变量等待着它的使用join()方法终止,但即使该变量被析构,该线程也将继续运行。
#include <boost/thread.hpp> #include <iostream> void wait(int seconds) { boost::this_thread::sleep(boost::posix_time::seconds(seconds)); } void thread() { try { for (int i = 0; i < 5; ++i) { wait(1); std::cout << i << std::endl; } } catch (boost::thread_interrupted&) { } } int main() { boost::thread t(thread); wait(3); t.interrupt(); t.join(); return 0; }
在一个线程对象上调用interrupt()会中断相应的线程。中断意味着一个类型为boost::thread_interrupted的异常,会在这个线程中抛出,只有在线程达到中断点时才会发生。如果给定的线程不包含任何中断点,简单调用interrupt()就不会起作用。每当一个线程中断点,它就会检查interrupt()是否被调用过。只有被调用过了,boost::thread_interrupted异常才会相应的抛出。sleep()函数为一个程序中断点。
2. 同步