2012-03-14 57 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. 
}