我希望能够如下中断线程。

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 对象时未定义。我怎样才能解决这个问题?

最佳答案

使用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();

}

07-28 13:10