Interrupting boost thread

2019-07-23 23:54发布

问题:

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?

回答1:

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

}


回答2:

Boost thread is movable, so you can do something like:

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

If you want to pass it around (e.g. as an argument to the function), you'll probably want to use a pointer or a reference:

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

(This probably needs more. For example, as written, if you execute mainThread( "start" ) twice in a row, you'll detach the first thread, and never be able to refer to it again.)

Another alternative would be to use boost::shared_ptr.



回答3:

This isn't a question about boost::thread, it's about scope:

this:

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

is the same as this:

if(Condition) 
{
    MyType foo;
} // after this brace, foo no longer exists, so...
foo.method(); // won't work, no foo in scope

Notice that the answers above all do something like:

MyType foo:
if (Condition)
    foo.method(); // works because now there is a foo in scope
else
{
    foo.otherMethod(); // foo in scope here, too.
}