C++ boost thread学习(二)

线程中断

在一个线程对象上调用 interrupt() 会中断相应的线程,并会在这个线程中抛出一个类型为 boost::thread_interrupted 的异常。

如果给定的线程不包含任何中断点,简单调用interrupt就不会起作用。 每当一个线程中断点,它就会检查interrupt是否被调用过。只有被调用过了, boost::thread_interrupted 异常才会相应地抛出。

Boost.Thread定义了一系列的中断点,例如sleep() 函数,由于sleep() 在这个例子里被调用了五次,该线程就检查了五次它是否应该被中断。然而sleep()之间的调用,却不能使线程中断。

一旦该程序被执行,它只会打印三个标准输出流。这是由于在main里3秒后调用 interrupt()方法。 因此,相应的线程被中断,并抛出一个 boost::thread_interrupted 异常。这个异常在线程内也被正确地捕获,catch 处理是空的。

Boost.Thread定义包括上述 sleep()函数等十个中断。 有了这些中断点,线程可以很容易及时中断。然而,他们并不总是最佳的选择,因为中断点必须事前读入以检查 boost::thread_interrupted 异常。


#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>

#include <iostream>

boost::mutex io_mutex;

using namespace std;

void wait(int seconds)
{
boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}

void interruptedThread()
{
try
{
for (int i = 0; i < 5; i++)
{
wait(1);
cout << i << endl;
}
}
catch (boost::thread_interrupted&)
{
cout << "thread_interrupted exception happened";
}
}

void testInteruptedThread()
{
boost::thread t(interruptedThread);
wait(3);
t.interrupt();
t.join();
}

int main(int argc, char* argv[])
{
testInteruptedThread();
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值