boost 线程 linux,Linux资源-Struts2框架(五)-【Boost】boost库中thread多线程详解5——谈谈线程中断_169IT.COM...

线程不是在任意时刻都可以被中断的。如果将线程中函数中的sleep()睡眠等待去掉,那么即使在主线程中调用interrupt()线程也不会被中断。

thread库预定义了若干个线程的中断点,只有当线程执行到中断点的时候才能被中断,一个线程可以拥有任意多个中断点。

thread库预定义了共9个中断点,它们都是函数,如下:

1. thread::join();

2. thread::timed_join();

3. condition_variable::wait();

4. condition_variable::timed_wait();

5. condition_variable_any::wait();

6. condition_variable_any::timed_wait();

7. thread::sleep();

8. this_thread::sleep();

9. this_thread::interruption_point()

这些中断点中的前8个都是某种形式的等待函数,表明线程在阻塞等待的时候可以被中断。

而最后一个位于子名字空间this_thread的interruption_point()则是一个特殊的中断点函数,它并不等待,只是起到一个标签的作用,表示线程执行到这个函数所在的语句就可以被中断。看看下面的例子:

namespace

{

boost::mutex io_mu;

void to_interrupt(const std::string& str)

{

// 如果在线程外部调用了this_thread->interrupt()

// 线程内部的以下这些检查点可以抛出boost::thread_interrupted异常

try

{

boost::this_thread::disable_interruption();

for (int i = 0; i < 5; ++i)

{

boost::mutex::scoped_lock lock(io_mu);

PRINT_DEBUG(i);

PRINT_DEBUG(std::boolalpha << boost::this_thread::interruption_enabled());

// PRINT_DEBUG(std::boolalpha << boost::this_thread::interruption_requested());

if (i == 2)

{

PRINT_DEBUG(std::boolalpha << boost::this_thread::interruption_enabled());

boost::this_thread::interruption_point();

PRINT_DEBUG(std::boolalpha << boost::this_thread::interruption_enabled());

}

}

}

catch (boost::thread_interrupted &)

{

}

}

}

void test_thread_interrupt()

{

boost::thread t(to_interrupt, "hello");

// 中断函数

t.interrupt();

t.join();

}运行结果:

2013-01-02 11:00:44 263 [8272] DEBUG - 0

2013-01-02 11:00:44 266 [8272] DEBUG - 1

2013-01-02 11:00:44 269 [8272] DEBUG - 2如果注释boost::this_thread::interrupt_point了,则结果如下:2013-01-02 11:02:06 555 [5168] DEBUG - 0

2013-01-02 11:02:06 559 [5168] DEBUG - 1

2013-01-02 11:02:06 561 [5168] DEBUG - 2

2013-01-02 11:02:06 564 [5168] DEBUG - 3

2013-01-02 11:02:06 567 [5168] DEBUG - 4

作者:huang_xw 发表于2013-1-2 11:52:05 原文链接

阅读:60 评论:0 查看评论

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值