首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在禁用中断时中断boost::thread

在禁用中断时中断boost::thread
EN

Stack Overflow用户
提问于 2011-03-03 00:48:52
回答 1查看 1.7K关注 0票数 1

在使用boost::Threads时,我遇到了这个中断问题。当我在线程B上从线程A执行boost::thread_interrupt时,而B禁用了中断(boost::this_thread::disable_interrupts di),中断似乎丢失了。也就是说,如果我在启用中断之后放入一个boost::thread::interruption_point(),它不会抛出boost::thread_interrupted异常。

这是预期的行为,还是我做错了什么?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-03-03 03:38:10

文档中没有提到,当线程B重新启用中断时,会重新触发中断。我已经尝试了一个简单的测试程序,可以确认您所描述的行为。

重新启用中断后,您可以检查this_thread::interruption_requested(),以查看在禁用中断的同时是否请求了中断。如果确实请求了中断,您可以自己抛出thread_interrupted异常。

这是一个演示这一点的工作程序:

代码语言:javascript
复制
#include <boost/thread.hpp>
#include <iostream>

using namespace std;
using namespace boost;

void threadB()
{
    int ticks = 0;
    this_thread::disable_interruption* disabler = 0;
    try
    {
        while (ticks < 20)
        {
            if (ticks == 5)
            {
                cout << "Disabling interruptions\n";
                disabler = new this_thread::disable_interruption;
            }
            if (ticks == 15)
            {
                cout << "Re-enabling interruptions\n";
                delete disabler;
                if (this_thread::interruption_requested())
                {
                    cout << "Interrupt requested while disabled\n";
                    throw thread_interrupted();
                }
            }
            cout << "Tick " << ticks << "\n";
            thread::sleep(get_system_time() + posix_time::milliseconds(100));
            ++ticks;
        }
    }
    catch (thread_interrupted)
    {
        cout << "Interrupted\n";
    }
}

int main()
{
    thread b(&threadB);
    thread::sleep(get_system_time() + posix_time::milliseconds(1000));
    b.interrupt();
    cout << "main -> Interrupt!\n";
    b.join();
}

希望这能有所帮助。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5170647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档