#include <iostream>
#include <fstream>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
void wait(int seconds)
{
boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}
void threadfun1()
{
for (int i = 0; i < 5; ++i)
{
wait(1);
std::cout<<i<<"\n";
}
}
void threadfun2()
{
try
{
for (int i = 0; i < 5; ++i)
{
wait(1);
std::cout<<i<<"\n";
}
}
catch (boost::thread_interrupted&)
{
std::cout<<"thread_interrupted\n";
}
}
void test_thread_wait1()
{
boost::thread t(&threadfun1);
t.join();// join()方法是一个阻塞调用:它可以暂停当前线程,直到调用join()的线程运行结束。
}
void test_thread_wait2()
{
boost::thread t(&threadfun2);
wait(3);
t.interrupt();
t.join();
}
void test_thread_wait3()
{
boost::thread t(&threadfun2);
// timed_join()方法同样也是一个阻塞调用:它可以暂停当前线程,
// 直到调用join()的线程运行结束或者超时
t.timed_join(boost::posix_time::seconds(1));
}
void test_thread_wait4()
{
boost::thread t(&threadfun2);
wait(3);
// 当thread 与线程执行体分离时,线程执行体将不受影响地继续执行,
// 直到运行结束,或者随主线程一起结束。
t.detach();
// 此时join无作用
t.join();
// t不再标识任何线程 {Not-any-thread}
assert(t.get_id() == boost::thread::id());
std::cout<<" t.get_id() = "<<t.get_id()<<std::endl;
}
void main ()
{
test_thread_wait1();
//test_thread_wait2();
//test_thread_wait3();
//test_thread_wait4();
system("pause");
}
test_thread_wait1();
0
1
2
3
4
请按任意键继续. . .
test_thread_wait2();
0
1
2
thread_interrupted
请按任意键继续. . .
test_thread_wait3();
0
请按任意键继续. . . 1
2
3
4
test_thread_wait4();
0
1
t.get_id() = {Not-any-thread}
2
请按任意键继续. . . 3
4