Search code examples
c++multithreadingc++11stdthread

How can I declare an std::thread anonymously?


Consider the following short program:

#include <thread>

int Foo() {
while (1);
}

int main(){
    std::thread t(Foo);
    std::thread s(Foo);

    // (std::thread(Foo));

    t.join();
}

This compiles and runs (forever), with

g++ -Wl,--no-as-needed DoubleBufferTest.cc -o DoubleBufferTest -std=c++0x -pthread

In the commented out line, I am trying to use the technique described here to declare a new thread anonymously. However, when that line is commented back in, I can compile but running gives the following error:

terminate called without an active exception            
Aborted (core dumped)                                   

How can I correctly declare a thread anonymously?

Note, I am on g++ 4.4.7.


Solution

  • You can do it like this:

    std::thread(Foo).detach();