You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Renaming CP.25 raii_thread, and fixing CP.26 detached_thread #925
The PR for this is now ready to merge into GSL here: microsoft/GSL#504
IMO the design looks fine. But do we really want to use the name "raii_thread"? Yes, that's technically what it is (for those who like using that acronym), but why not "joining_thread" or "scoped_thread"? ... or, best of all, "thread"!
Proposed resolution: Rename "raii_thread" to just gsl::thread. This type is what std::thread ought to have been, and it's identical to std::thread except that gsl::thread has a properly-joining destructor and does not have detach. And this is what namespaces are for. :)
CP.26 detached_thread
The GSL PR has split out "raii_thread" because I suggested "detached_thread" was problematic and less recommendable. So we should also do something about CP.26 which recommends "detached_thread" -- I think detaching is an antipattern we should not encourage, as Hans and others have pointed out many times (e.g., orderly shutdown is at best problematic and usually impossible).
Proposed resolution:
Drop "gsl::detached_thread" and the current CP.26.
Replace CP.26 with the inverse Guideline that says "never detach threads" (that’s an unsafe antipattern). Include an example showing how you can never safely join or interact with it during static destruction. Enforcement: Flag any call to std::thread::detach. What to do instead: Just stick a normal gsl::thread in a global object or container and then ignore it if you want… but it means better more-orderly shutdown by default plus the ability to actually join with it if you do want to refer to it later.
Reacted by Jonathan Wakely, Galik, Arvid Norberg, Daniel Engelke and blakehawkins
Per our editor's discussion, people don't consistently write namespace names. The same name in different namespaces might lead to confusion. When we talk about it, we're often not precise about which we are talking about. If it's something different, it should have a different name. Possibly joining_thread?
@jwakely, can you comment on the detached thread issue? Does this work in the light of a long POSIX tradition?
TC++PL4 says "do not detach a thread unless you absolutely have to".
PPP doesn't bother to mention detach, so it doesn't warn".
The only reason we don't have "never detach a thread" is caution.I think the time has come.
(re)naming of raii_thread:
thread - I think recycling "thread" in gsl would cause confusion and accusations that we were trying to change the standard. So, no.
raii_thread - I like it :-)
joining_thread - maybe, but it doesn't grab me
scoped_thread - I'm against all "scoped_*" names for names in scopes, but some people like them :-(
Reacted by blakehawkins, AraHaan and Matthieu Poullet
The only reason to detatch threads is probaly to execute coroutines in a separate thread. The way python does it is that it uses an event loop and itterators as ways to scedule coroutines as tasks and each task would have a new temporary thread it is ran in. And to be honest I think a major break for couroutines in C++ is to have someone who knows python and C++ to at least copy some things from python's asyncio. At least asyncio on python can give hints.
However even with coroutines, there is no garrentee that functions can run without possible race conditions. However most race contitions come from things like:
// Example loop till 255 is reached.for (int i = 0; i < 255; ++i) {
// do stuff.// they accidentally do this. Do not do this as it can make an race condition.for (int i = 0; i > 0; ++i) {
// other things.
}
}
But yeah this can at most give hints on how to do it (However you guys might not want an event loop for exectuting coroutines, but you never know).
sometimes you just love having to source dive into things. But their C code is so much cancer code. (makes me really want to make my own rewrite to latest python master branch to be total C++ to be a lot easier on my eyes)
Yes, but I think that P0206 is evidence in favor of GSL using the name joining_thread. In Jacksonville, P0206 was encouraged by a consensus of LEWG modulo finalizing a name (the group was evenly split between joining_thread and simple_thread and left it to the author to pick a name; wiki notes here, requires password), and then in Oulu was killed by controversy in a larger group but that was unrelated to the name (wiki notes here, requires password).
So the name joining_thread is both (a) popular with the people who want the feature, and (b) not going to be used by the standard or a TS anytime soon. That makes it just about perfect.
BTW, I don't think we want to set a precedent that an RAII type should be named "raii_"... that would be a huge number of types. :)
It gives me pause to push the notion of the proposed std::joining_thread being what std::thread should've always been, and I am concerned about the confusion of different libraries giving different semantics to one name, namespaced or not. Chalk this up as a +1 for gsl::joining_thread.
I took a good look at Howard's code and couldn't see any races. The threads exit after unlocking the mutex, so don't access anything after the cv.notify_all() calls. The main thread won't exit until the other threads have at least set their done flag and released the mutex (so the condition variable can relock it). It's possible the worker threads will still be in the process of exiting (after unlocking the mutex, before actually stopping running) when main returns, but the other threads don't access any globals at that point.
Right. This is a good example of a case where it is important to do the cv notify prior to unlocking the mutex. There is no way for main to act on spurious wake up and notice that the thread's status has been set to indicate that the thread has ended, because main can't get the mutex lock. The very last thing the thread touches before exiting is unlocking the mutex. From then on it is the std::lib's responsibility to clean up the thread if the program ends before the thread is done exiting.
Had the mutex been unlocked, and then the cv notified, it would be theoretically possible for main to spuriously wake up and destruct the cv before the thread called notify_all on it, resulting in UB.
Now that I think of it, THAT would be a good guideline!
When notifying a condition_variable, default to doing it before you unlock the mutex instead of after. Rationale: It is never wrong to unlock after the notify, and it is sometimes wrong to unlock before the notify. And there is no performance penalty in unlocking after, as good implementations take this coding pattern into account.
Howard, thanks for the correction -- my "quick look" was too quick and I missed the careful use of the mutex and cv.
I think we're agreeing not to teach detaching as a default design choice.
I like your suggested condition_variable guideline, and I'll raise you one: I've long wished we had something like a "waitable_mutex" or "notifiable_mutex" abstraction in the standard library that encapsulated a mutex and an associated condition variable, so code that uses cv's in the most common patterns (all uses of the cv are supposed to be used with the same mutex) could avoid the need to remember to pass cv.wait() a lock to the right mutex. If you have a suggestion along that line it would be welcome!
@MikeGitb: We have half of it with the wait(lk, pred). I'd like to fully automate the pattern of
{
unique_lock hold{mut};
while ( ! /* the protected state is what we are waiting for */ )
cv.wait(hold); // unlock and reacquire/* main work */
}
With the predicate form, we have this much:
{
unique_lock hold{mut};
cv.wait(hold, []{ return/* the protected state is what we are waiting for */; });
/* main work */
}
That's not too bad. But I was thinking of a way to avoid repeating cv and hold separately there, to avoid the opportunity to accidentally pass to cv.wait a lock that actually has locked a different mutex. Something like:
{
conditional_lock hold{mutwithcv, []{ return/* the protected state is what we are waiting for */; }};
/* main work */
}
so that the mutex and cv are bundled and we can't make the mistake of using the wrong one. This doesn't cover all cv cases, but it covers common ones. But I admit I haven't tried very hard to define this (or look for it -- I'd love to be told to just use something that already exists that I should already know about but don't).
@hsutter: Sorry, I deleted my original post - I thought no one had seen it ;)
I made the mistake of only thinking about the signaling part, for which I still think a semaphore would be the best solution in 99% of the cases.
However, I ignored the fact that you very often need to modify some shared data right after the thread is woken up or right before the signaling anyway - just as you hinted in your example. With semaphores instead of CV+lock or your proposed mechanism this would obviously require an additional mutex or an otherwise threadsafe (e.g. lock-free) data structure.
I hope I have resolved this one. It's obviously tricky. Please review carefully.
raii_thread is now joining_thread and detached_thread is gone.
There is a "don't detach()" rule is there together with a recommendation to use scope to control lifetime of threads
Most rules about std::thread are gone, but I acknowledge that std::thread isn't going away (and joining_thread is a std::thread)
I see you've discussed a lot and there are different views, but one major issue with joining_thread is that when it's a member of some object and the object is being destroyed from within thread (e.g. via shared_ptr), this usually leads to deadlock.
This is likely pattern used in 'worker' or 'event loop' classes, where class has internal thread(s) and interface to accept and dispatch messages, usually with shared ownership.
Other N cents:
Therefore I saw quite opposite recommendation: use only detached thread. Besides the system does proper cleanup it makes programmer think not in term of 'threads' but rather about 'communication'.
Some reasoning:
thread itself is not a real resource which must be handled like open file. At least in posix and windows threads system takes care of resources after return from function.
join() provides very limited synchronization and signaling, better to use mutex and CV.
Guideline give example of heartbeat() function and reason that 'detach makes it harder to monitor and communicate with the detached thread'. Fundamental problem I see here is that you don't communicate with thread, you communicate with object. For heartbeat there should be a Heartbeat_monitor class with detached thread and bool is_alive() const function which you communicate through.
I've looked at examples in Guidelines and it feels that wherever thread is used with plain function and then joined, the CP.4 rule and std::async() should be used instead.
Actually, what is the benefit of joining_thread over std::async?
Note on shared ownership: I find it very useful because this nicely solves 2 issues: 'CP.22 Never call unknown code while holding a lock' and memory management. So I had shared_ptr also attached to every callback to be dispatched, which kept the object alive while callback was in the queue or being executed, thus message loop could be safely destroyed even from thread it owns, e.g. if callback releases last 'public' reference to the message loop.
Activity
cubbimew commentedon May 9, 2017
this would also close the old To-do issue that says "is there a good reason to detach threads?"
AndrewPardoe commentedon May 15, 2017
Per our editor's discussion, people don't consistently write namespace names. The same name in different namespaces might lead to confusion. When we talk about it, we're often not precise about which we are talking about. If it's something different, it should have a different name. Possibly
joining_thread?@jwakely, can you comment on the detached thread issue? Does this work in the light of a long POSIX tradition?
jwakely commentedon May 16, 2017
I'm sure "never detach threads" will upset someone, but I don't expect strong enough objections that it would prevent that guideline.
BjarneStroustrup commentedon May 16, 2017
TC++PL4 says "do not detach a thread unless you absolutely have to".
PPP doesn't bother to mention detach, so it doesn't warn".
The only reason we don't have "never detach a thread" is caution.I think the time has come.
BjarneStroustrup commentedon May 16, 2017
(re)naming of raii_thread:
thread - I think recycling "thread" in gsl would cause confusion and accusations that we were trying to change the standard. So, no.
raii_thread - I like it :-)
joining_thread - maybe, but it doesn't grab me
scoped_thread - I'm against all "scoped_*" names for names in scopes, but some people like them :-(
jwakely commentedon May 16, 2017
If recycling a name from
stdis a concern, be aware of http://wg21.link/p0206AraHaan commentedon May 16, 2017
The only reason to detatch threads is probaly to execute coroutines in a separate thread. The way python does it is that it uses an event loop and itterators as ways to scedule coroutines as
tasksand eachtaskwould have a new temporarythreadit is ran in. And to be honest I think a major break for couroutines in C++ is to have someone who knows python and C++ to at least copy some things from python's asyncio. At least asyncio on python can give hints.However even with coroutines, there is no garrentee that functions can run without possible race conditions. However most race contitions come from things like:
Sadly the compiler does allow this too.
galik commentedon May 16, 2017
What about
gsl::local_thread? Being local to the scope or object it is defined in?jwakely commentedon May 16, 2017
It's not local if you return it from a function, or have it as a data member of a class, or a global, or a member of a global container.
AraHaan commentedon May 16, 2017
true, anyway the following files can help implement coroutines (I think) into C++ v. next:
But yeah this can at most give hints on how to do it (However you guys might not want an event loop for exectuting coroutines, but you never know).
sometimes you just love having to source dive into things. But their C code is so much cancer code. (makes me really want to make my own rewrite to latest python master branch to be total C++ to be a lot easier on my eyes)
jwakely commentedon May 16, 2017
I don't see how coroutines are on-topic here.
hsutter commentedon May 16, 2017
@jwakely wrote:
Yes, but I think that P0206 is evidence in favor of GSL using the name
joining_thread. In Jacksonville, P0206 was encouraged by a consensus of LEWG modulo finalizing a name (the group was evenly split betweenjoining_threadandsimple_threadand left it to the author to pick a name; wiki notes here, requires password), and then in Oulu was killed by controversy in a larger group but that was unrelated to the name (wiki notes here, requires password).So the name
joining_threadis both (a) popular with the people who want the feature, and (b) not going to be used by the standard or a TS anytime soon. That makes it just about perfect.BTW, I don't think we want to set a precedent that an RAII type should be named "raii_"... that would be a huge number of types. :)
villevoutilainen commentedon May 16, 2017
It gives me pause to push the notion of the proposed std::joining_thread being what std::thread should've always been, and I am concerned about the confusion of different libraries giving different semantics to one name, namespaced or not. Chalk this up as a +1 for gsl::joining_thread.
villevoutilainen commentedon May 16, 2017
Note that scoped_thread has some downsides; the proposed joining_thread can move across scopes, it's not bound to a particular scope.
22 remaining items
jwakely commentedon May 17, 2017
I took a good look at Howard's code and couldn't see any races. The threads exit after unlocking the mutex, so don't access anything after the
cv.notify_all()calls. The main thread won't exit until the other threads have at least set their done flag and released the mutex (so the condition variable can relock it). It's possible the worker threads will still be in the process of exiting (after unlocking the mutex, before actually stopping running) whenmainreturns, but the other threads don't access any globals at that point.HowardHinnant commentedon May 18, 2017
Right. This is a good example of a case where it is important to do the cv notify prior to unlocking the mutex. There is no way for
mainto act on spurious wake up and notice that the thread's status has been set to indicate that the thread has ended, becausemaincan't get the mutex lock. The very last thing the thread touches before exiting is unlocking the mutex. From then on it is the std::lib's responsibility to clean up the thread if the program ends before the thread is done exiting.Had the mutex been unlocked, and then the cv notified, it would be theoretically possible for main to spuriously wake up and destruct the cv before the thread called
notify_allon it, resulting in UB.HowardHinnant commentedon May 18, 2017
Now that I think of it, THAT would be a good guideline!
When notifying a condition_variable, default to doing it before you unlock the mutex instead of after. Rationale: It is never wrong to unlock after the notify, and it is sometimes wrong to unlock before the notify. And there is no performance penalty in unlocking after, as good implementations take this coding pattern into account.
hsutter commentedon May 18, 2017
Howard, thanks for the correction -- my "quick look" was too quick and I missed the careful use of the mutex and cv.
I think we're agreeing not to teach detaching as a default design choice.
I like your suggested
condition_variableguideline, and I'll raise you one: I've long wished we had something like a "waitable_mutex" or "notifiable_mutex" abstraction in the standard library that encapsulated a mutex and an associated condition variable, so code that uses cv's in the most common patterns (all uses of the cv are supposed to be used with the same mutex) could avoid the need to remember to passcv.wait()a lock to the right mutex. If you have a suggestion along that line it would be welcome!hsutter commentedon May 18, 2017
@MikeGitb: We have half of it with the
wait(lk, pred). I'd like to fully automate the pattern of{ unique_lock hold{mut}; while ( ! /* the protected state is what we are waiting for */ ) cv.wait(hold); // unlock and reacquire /* main work */ }With the predicate form, we have this much:
{ unique_lock hold{mut}; cv.wait(hold, []{ return /* the protected state is what we are waiting for */; }); /* main work */ }That's not too bad. But I was thinking of a way to avoid repeating
cvandholdseparately there, to avoid the opportunity to accidentally pass tocv.waita lock that actually has locked a different mutex. Something like:{ conditional_lock hold{mutwithcv, []{ return /* the protected state is what we are waiting for */; }}; /* main work */ }so that the mutex and cv are bundled and we can't make the mistake of using the wrong one. This doesn't cover all cv cases, but it covers common ones. But I admit I haven't tried very hard to define this (or look for it -- I'd love to be told to just use something that already exists that I should already know about but don't).
jwakely commentedon May 18, 2017
Building that on top of Olivier's http://wg21.link/p0126 would be optimal, but it's still going through redesign in SG1.
jwakely commentedon May 18, 2017
@HowardHinnant
I'll make a note to include it in the CV guidelines, writing them up has been on my TODO list for ages
MikeGitb commentedon May 18, 2017
@hsutter: Sorry, I deleted my original post - I thought no one had seen it ;)
I made the mistake of only thinking about the signaling part, for which I still think a semaphore would be the best solution in 99% of the cases.
However, I ignored the fact that you very often need to modify some shared data right after the thread is woken up or right before the signaling anyway - just as you hinted in your example. With semaphores instead of CV+lock or your proposed mechanism this would obviously require an additional mutex or an otherwise threadsafe (e.g. lock-free) data structure.
Don't detach, rename raii_thread to joining_thread
BjarneStroustrup commentedon May 21, 2017
I hope I have resolved this one. It's obviously tricky. Please review carefully.
raii_thread is now joining_thread and detached_thread is gone.
There is a "don't detach()" rule is there together with a recommendation to use scope to control lifetime of threads
Most rules about std::thread are gone, but I acknowledge that std::thread isn't going away (and joining_thread is a std::thread)
ytimenkov commentedon Jun 22, 2017
I see you've discussed a lot and there are different views, but one major issue with
joining_threadis that when it's a member of some object and the object is being destroyed from within thread (e.g. via shared_ptr), this usually leads to deadlock.This is likely pattern used in 'worker' or 'event loop' classes, where class has internal thread(s) and interface to accept and dispatch messages, usually with shared ownership.
Other N cents:
Therefore I saw quite opposite recommendation: use only detached thread. Besides the system does proper cleanup it makes programmer think not in term of 'threads' but rather about 'communication'.
Some reasoning:
Guideline give example of
heartbeat()function and reason that 'detachmakes it harder to monitor and communicate with the detached thread'. Fundamental problem I see here is that you don't communicate with thread, you communicate with object. For heartbeat there should be aHeartbeat_monitorclass with detached thread andbool is_alive() constfunction which you communicate through.I've looked at examples in Guidelines and it feels that wherever thread is used with plain function and then joined, the CP.4 rule and
std::async()should be used instead.Actually, what is the benefit of joining_thread over std::async?
Note on shared ownership: I find it very useful because this nicely solves 2 issues: 'CP.22 Never call unknown code while holding a lock' and memory management. So I had shared_ptr also attached to every callback to be dispatched, which kept the object alive while callback was in the queue or being executed, thus message loop could be safely destroyed even from thread it owns, e.g. if callback releases last 'public' reference to the message loop.
Notify condition_variable under the lock.
Notify condition_variable under the lock.