Alex Rivera | Logout

In C++11, what is the point of a thread which "does not represent a thread of execution"?

Asked 2011-09-26T03:20:58.153
50

Looking over the new threading stuff in C++11 to see how easily it maps to pthreads, I notice the curious section in the thread constructor area:

thread();
Effects: Constructs a thread object that does not represent a thread of execution.
Postcondition: get_id() == id()
Throws: Nothing.

In other words, the default constructor for a thread doesn't actually seem to create a thread. Obviously, it creates a thread object, but how exactly is that useful if there's no backing code for it? Is there some other way that a "thread of execution" can be attached to that object, like thrd.start() or something similar?

Edit
Report

1 Answer

24

It means the same thing as this:

 std::vector<int> emptyList;

emptyList is empty. Just like a default-constructed std::thread. Just like a default-constructed std::ofstream doesn't open a file. There are perfectly reasonable reasons to have classes that default construct themselves into an empty state.


If you have an empty thread:

std::thread myThread;

You can actually start the thread by doing this:

myThread = std::thread(f, ...);

Where f is some callable thing (function pointer, functor, std::function, etc), and ... are the arguments to be forwarded to the thread.

answered 2011-09-26T03:27:58.120

Your Answer