Skip to content

Renaming CP.25 raii_thread, and fixing CP.26 detached_thread #925

Closed

Description

@hsutter

CP.25 raii_thread

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.

Activity

  1. cubbimew commented on May 9, 2017

    @cubbimew
    Member

    this would also close the old To-do issue that says "is there a good reason to detach threads?"

  2. AndrewPardoe commented on May 15, 2017

    @AndrewPardoe
    Contributor

    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?

  3. jwakely commented on May 16, 2017

    @jwakely
    Contributor

    I'm sure "never detach threads" will upset someone, but I don't expect strong enough objections that it would prevent that guideline.

  4. BjarneStroustrup commented on May 16, 2017

    @BjarneStroustrup
    Contributor

    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.

  5. BjarneStroustrup commented on May 16, 2017

    @BjarneStroustrup
    Contributor

    (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 :-(

  6. AraHaan commented on May 16, 2017

    @AraHaan

    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.
        }
    }

    Sadly the compiler does allow this too.

  7. galik commented on May 16, 2017

    @galik
    Contributor

    What about gsl::local_thread? Being local to the scope or object it is defined in?

  8. jwakely commented on May 16, 2017

    @jwakely
    Contributor

    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.

  9. AraHaan commented on May 16, 2017

    @AraHaan

    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)

  10. jwakely commented on May 16, 2017

    @jwakely
    Contributor

    I don't see how coroutines are on-topic here.

  11. hsutter commented on May 16, 2017

    @hsutter
    ContributorAuthor

    @jwakely wrote:

    If recycling a name from std is a concern, be aware of http://wg21.link/p0206

    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. :)

  12. villevoutilainen commented on May 16, 2017

    @villevoutilainen

    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.

  13. villevoutilainen commented on May 16, 2017

    @villevoutilainen

    Note that scoped_thread has some downsides; the proposed joining_thread can move across scopes, it's not bound to a particular scope.

  14. 22 remaining items

  15. jwakely commented on May 17, 2017

    @jwakely
    Contributor

    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.

  16. HowardHinnant commented on May 18, 2017

    @HowardHinnant

    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.

  17. HowardHinnant commented on May 18, 2017

    @HowardHinnant

    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.

  18. hsutter commented on May 18, 2017

    @hsutter
    ContributorAuthor

    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!

  19. hsutter commented on May 18, 2017

    @hsutter
    ContributorAuthor

    @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).

  20. jwakely commented on May 18, 2017

    @jwakely
    Contributor
  21. jwakely commented on May 18, 2017

    @jwakely
    Contributor

    @HowardHinnant

    When notifying a condition_variable, default to doing it before you unlock the mutex instead of after.

    I'll make a note to include it in the CV guidelines, writing them up has been on my TODO list for ages

  22. MikeGitb commented on May 18, 2017

    @MikeGitb

    @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.

  23. BjarneStroustrup commented on May 21, 2017

    @BjarneStroustrup
    Contributor

    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)

  24. ytimenkov commented on Jun 22, 2017

    @ytimenkov

    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:

    1. 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.
    2. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions