c++ - 我们如何中断主线程

标签 c++ linux boost-thread

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

找不到主线程对应的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;
        }
}

最佳答案

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


如果你想在当前线程上“应用” sleep ,使用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();
}

关于c++ - 我们如何中断主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30571271/

相关文章:

c++ - 使用 C 在收据打印机中打印图像

c++ - 在线校准相机时校准相机时出现 OpenCV 运行时错误

c++ - 显式模板函数和方法特化

linux - boost::thread::try_join_for() 函数出错

c++ - linux下用boost::thread创建boost::asio工作线程

c++ - 执行简单的 boost 线程程序时出错

c# - 关于 "GUI in C# and code in C++"

c - 相当于ping的网络设备模块

linux - 当我安装 linux 时,如何发现我的特定计算机是否会出现问题?

linux - 用于复制、重命名和更改文件所有者权限的 Shell 脚本