[cpp-threads] Asynchronous Execution Issues

Herb Sutter hsutter at microsoft.com
Mon Apr 27 14:48:11 BST 2009


> Let me be more explicit.  Let's assume that I have a thread that's
> created by, and used by, some library.  The library detaches the
> thread.  Since the library designed wants to allow the process to shut
> down safely without the use of quick_exit, it provides an API call to
> shut down this helper thread before process exit.  My mental picture of
> how this could work was something like
> 
> atomic<bool> shutdown_requested;
> 
> void shutdown_helper()
> {
>   shutdown_requested = true;
>   // wait for helper thread to acknowledge request using cv, future or
> the like.
> }
> 
> The helper thread occasionally tests shutdown_requested, and if it's
> set acknowledges the request by notifying the cv and then exits.
> 
> I think we're saying that this doesn't work, because destructors will
> be invoked between the notification (or setting the promise) and the
> thread actually exiting.  Those destructors may continue to be invoked
> past the beginning of process shutdown.  Since the destructors are
> likely to call into the library, the program has undefined behavior,
> and may crash in practice.

I haven't been following this, but why not arrange for a guard object that is destroyed last and signals the cv from its destructor?

  void thread_mainline( CV& cv ) {
    Guard g(cv);
    ...
  } // ~Guard signals cv

> It seems to me that this is a fairly fundamental problem, which is
> certainly not limited to asyncs.  It seems to me that the presence of
> detached threads really requires the use of quick_exit() (or a
> nonterminating program).  Effectively, the combination of detached
> threads and static destructors doesn't ever work.
> 
> Does anyone see a way to get any detached_thread to safely shut down
> without calling quick_exit()?  (I'm assuming that the detached thread
> is cooperative enough to poll a flag regularly, to get around the
> absence of cancellation.)

Yes, it would have to cooperate.

> Hans
> 
> 
> --
> cpp-threads mailing list
> cpp-threads at decadentplace.org.uk
> http://www.decadentplace.org.uk/cgi-bin/mailman/listinfo/cpp-threads




More information about the cpp-threads mailing list