我正在使用下面的简单程序为命令行上指定的参数生成 sleep 。
找不到主线程对应的boost::thread
对象。使用空的 thread_obj
,sleep
正在工作,但 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
。
恐怕你不能打断主线程。但是,您可以在您立即加入的单独线程上运行主程序:
#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/