Search code examples
c++multithreadingboostboost-thread

Interrupting boost thread


I would like to be able to interrupt a thread as follows.

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() is not possible because thrd object is undefined when I try to interrupt it. How can I fix this?


Solution

  • Use the 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();
    
    }