2012-03-14 12 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を使用してください:あなたは(関数の引数として例えば)それを周りに渡す場合

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

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

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

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

} 
1

ブーストスレッドあなたのような何かを行うことができますので、移動可能です。 、 ポインタや参照を使用することをお勧めします:

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

(これはおそらくもっと必要です。たとえば、あなたが2回連続 mainThread("start")を実行した場合、書かれたように、あなたが最初のスレッド、 を切り離し、決して再びそれを参照できるようになります。)

別の方法としては、ブーストを使用することです:: shared_ptrの。この

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

はこれと同じである:

+1

最初のコードの 'else if'では、' isStop'かそれに似たものか、 'isStart'ですか? –

+0

@ AdriC.S。はい。私はそれを修正します。 –

0

これは、ブースト::スレッドについての質問ではありませんが、それは適用範囲についてです

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. 
}