Home > Software design >  Why can't call std::thread.join() more than once for a given thread?
Why can't call std::thread.join() more than once for a given thread?

Time:09-14

I'm new to C multi-threaded programming, and I encountered some difficulties about the join() function while reading a book:

The act of calling join() also cleans up any storage associated with the thread, so the std::thread object is no longer associated with the now-finished thread; it isn’t associated with any thread. This means that you can call join() only once for a given thread; once you’ve called join(), the std::thread object is no longer joinable, and joinable() will return false.

What does "storage associated with the thread" specifically mean, and why is it cleaning up the storage associated with the thread when calling join()? Can anyone explain the principles behind this?

CodePudding user response:

what does "storage associated with the thread" specific mean.

Mostly it means the thread's call stack. Probably a few megabytes, but they don't make it easy to find out exactly how much space is allocated or, provide any well defined way to change it. See How to set the stacksize with C 11 std::thread

CodePudding user response:

The thread storage does nothing to do with the thread stack as in the other answer. When the thread terminates/finishes, all thread resources are freed except one in the OS kernel structures, that keeps thread exit status and possible other data used by OS. Joining just removes that data, OS forgets that thread for ever, further access to the thread is undefined behavior, for example can lead to unpredictable joining to a newly created thread.

  • Related