【问题标题】:How can we interrupt the main thread我们如何中断主线程
【发布时间】:2015-08-14 18:44:50
【问题描述】:

我正在使用下面的简单程序为命令行上指定的参数生成睡眠。

我找不到对应于主线程的boost::thread 对象。使用空的thread_objsleep 正在工作,但 boost::thread 对象在我运行程序时不会被中断。

那么有什么特别的原因可以解释为什么我没有收到boost::thread 对象的中断吗?

#include<iostream>
#include<boost/thread/thread.hpp>
#include<boost/date_time/date.hpp>

using namespace boost;
using namespace std;

boost::thread thread_obj;
boost::thread thread_obj1;

void func(void)
{
        char x;
        cout << "enter y to interrupt" << endl;
        cin >> x;
        if(x == 'y')
        {
                cout << "x = 'y'" << endl;
                thread_obj.interrupt();
                cout << "thread interrupt" << endl;
        }
}

int main(int argc,char **argv)
{
        thread_obj1 = boost::thread(&func);
        boost::system_time const timeout = boost::get_system_time() + boost::posix_time::seconds(atoi(argv[1]));
        try
        {
                boost::this_thread::sleep(timeout);
        } catch(boost::thread_interrupted &)
        {
                cout <<"thread interrupted" << endl;
        }
}

【问题讨论】:

  • 不知道你在用thread_obj做什么:它没有附加线程!
  • @LightnessRacesinOrbit boost::Thread_obj 只是为了应用睡眠而创建的......有可能这样做......??
  • 没有。睡眠将应用在哪个线程上?这没有意义。
  • 在 boost::thread 的 thread_obj 对象上......
  • @MaulikPanchal:我想你误解了boost::thread 对象是什么。这就是它没有做你想做的事情的具体原因。或许你可以明确一下你想中断哪个线程,从哪里中断,你希望从哪里休眠。

标签: c++ linux boost-thread


【解决方案1】:

我认为不可能在主线程上使用中断点(因为 boost 无法控制它)。中断点依赖于相当多的 Boost Thread 特定的隐藏机制。


如果您想在当前线程上“应用”睡眠,请使用 this_thread

恐怕你不能中断主线程。但是,您可以在您立即加入的单独线程上运行主程序:

Live On Coliru

#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/date_time/date.hpp>

using namespace boost;
using namespace std;

boost::thread thread_obj;
boost::thread thread_obj1;

void func(void)
{
    char x;
    cout << "enter y to interrupt" << endl;
    cin >> x;
    if (x == 'y') {
        cout << "x = 'y'" << endl;
        thread_obj.interrupt();
        cout << "thread interrupt" << endl;
    }
}

void real_main() {
    boost::system_time const timeout = boost::get_system_time() + boost::posix_time::seconds(3);
    try {
        boost::this_thread::sleep(timeout);
    }
    catch (boost::thread_interrupted &) {
        cout << "thread interrupted" << endl;
    }
}

int main()
{
    thread_obj1 = boost::thread(&func);
    thread_obj = boost::thread(&real_main);
    thread_obj.join();
}

【讨论】:

  • Thnx @sehe...我知道这种创建线程的方法,但是没有任何方法可以像不创建单独的睡眠线程一样,我们可以直接在创建的thread_obj上应用中断函数...??
  • 嗯。我把那部分排除在答案之外:) 在我的评论中:stackoverflow.com/questions/30571271/…。现已编辑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
相关资源
最近更新 更多