C++ 我们如何中断主线程
我使用下面的简单程序为命令行中指定的参数生成一个sleep 我找不到与主线程对应的C++ 我们如何中断主线程,c++,linux,boost-thread,C++,Linux,Boost Thread,我使用下面的简单程序为命令行中指定的参数生成一个sleep 我找不到与主线程对应的boost::thread对象。使用emptythread\u obj,sleep正在工作,但boost::thread对象在我运行程序时不会被中断 那么,有没有什么具体的原因使我没有得到boost::thread对象的中断 #include<iostream> #include<boost/thread/thread.hpp> #include<boost/date_time/dat
boost::thread
对象。使用emptythread\u 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;
使用名称空间std;
boost::thread thread_obj;
boost::螺纹螺纹_obj1;
无效函数(无效)
{
字符x;
cout x;
如果(x='y')
{
cout我认为不可能在主线程上使用中断点(因为boost无法控制它)。I中断点依赖于相当多的boost线程特定的隐藏机制
如果要在当前线程上“应用”睡眠,请使用此线程
恐怕您不能中断主线程。但是,您可以在一个单独的线程上运行主程序,然后立即加入:
#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();
}
#包括
#包括
#包括
使用名称空间boost;
使用名称空间std;
boost::thread thread_obj;
boost::螺纹螺纹_obj1;
无效函数(无效)
{
字符x;
cout x;
如果(x='y'){
我不知道你在用线程obj做什么:没有线程连接到它!@LightnessRacesinOrbit boost::thread\u obj只是为了应用睡眠而创建的…有可能这样做吗…?没有。在哪个线程上应用睡眠?那没有意义。在boost::thread的线程obj对象上…@MaulikPanchal:我想你错了了解什么是boost::thread
对象。这就是它没有做你想做的事情的具体原因。也许你可以澄清你想中断哪个线程,从哪里中断,从哪里休眠,从哪里休眠。Thnx@sehe…我知道这个创建线程的方法,但没有创建独立线程的方法我们可以在创建的线程上直接应用中断函数…??嗯。我没有回答这个部分:)它在我的评论中:。现在编辑