中断提升线程

Ale*_*xey 2 c++ multithreading boost boost-thread

我希望能够按如下方式中断线程.

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

}
Run Code Online (Sandbox Code Playgroud)

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

kar*_*lip 5

使用移动赋值运算符:

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

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

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

}
Run Code Online (Sandbox Code Playgroud)