我们怎样才能打断主线程

时间:2015-06-01 10:33:57

标签: c++ linux boost-thread

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

我找不到与主线程对应的boost::thread对象。使用empt 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;
        }
}

1 个答案:

答案 0 :(得分:0)

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

如果你想&#34;申请&#34;在当前线程上使用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();
}