2012-03-14 58 views
2

我想能够中断一个线程如下。中断提升线程

void mainThread(char* cmd) 
{ 
    if (!strcmp(cmd, "start")) 
     boost::thread thrd(sender); //start thread 

    if (!strcmp(cmd, "stop")) 
     thrd.interrupt();  // doesn't work, because thrd is undefined here 

} 

thrd.interrupt()因为THRD对象是不确定的,当我试图中断它是不可能的。我怎样才能解决这个问题?

回答

5

使用move assignment operator

void mainThread(char* cmd) 
{ 
    boost::thread thrd; 

    if (!strcmp(cmd, "start")) 
     thrd = boost::thread(sender); //start thread 

    if (!strcmp(cmd, "stop")) 
     thrd.interrupt(); 

} 
1

升压线程是可移动的,所以你可以这样做:如果你想围绕它传递

boost::thread myThread; 
if (isStart) { 
    myThread = boost::thread(sender); 
else if (isStop) { 
    myThread.interrupt(); 
} 

(例如,作为参数传递给函数) , 你可能想要使用指针或参考:

void 
mainThread(std::string const& command, boost::thread& aThread) 
{ 
    if (command == "start") { 
     aThread = boost::thread(sender); 
    } else if (command == "stop") { 
     aThread.interrupt(); 
    } 
} 

(这可能需要更多。例如,写,如果你连续执行 mainThread("start")两次,你会脱离第一线, 和永远无法再次提及它。)

另一种方法是使用boost :: shared_ptr的。

+1

在第一个代码的'else if'中不应该是'isStop'或类似的东西或者'isStart'? – 2012-12-18 16:47:14

+0

@ AdriC.S。是。我会解决它。 – 2012-12-19 10:56:50

0

这不是一个关于升压::线程的问题,这是关于范围:

这样的:

if(Condition) 
    MyType foo; 
... // foo is out of scope 
foo.method(); // won't work, no foo in scope 

是一样的:

if(Condition) 
{ 
    MyType foo; 
} // after this brace, foo no longer exists, so... 
foo.method(); // won't work, no foo in scope 

注意,答案首先做类似的事情:

MyType foo: 
if (Condition) 
    foo.method(); // works because now there is a foo in scope 
else 
{ 
    foo.otherMethod(); // foo in scope here, too. 
}