Daemon Threads

Sean Kelly sean at invisibleduck.org
Tue Aug 7 22:14:49 PDT 2012


On Aug 7, 2012, at 5:41 PM, Alex Rønne Petersen <alex at lycus.org> wrote:

> On 07-08-2012 21:38, Sean Kelly wrote:
>> On Aug 7, 2012, at 9:36 AM, David <d at dav1d.de> wrote:
>> 
>>> I have a threaded connection:
>>> ...
>>> Since this is a daemon thread, I'd expect it to stop/terminate when the main thread stops. This is not the case (it keeps running), is this a known bug and how can I workaround this?
>> 
>> Daemon threads will keep running until the process terminates.  Forcibly halting them any earlier risks leaving mutexes they hold in a locked state, etc, which could break shutdown and hang the app.  Typically, you'll want to have a shared module dtor communicate to any daemon threads that it's time for them to halt, and block until a response is received if you want to ensure a clean shutdown.
>> 
> 
> Huh? From thread.di:
> 
>    /**
>     * Gets the daemon status for this thread.  While the runtime will wait for
>     * all normal threads to complete before tearing down the process, daemon
>     * threads are effectively ignored and thus will not prevent the process
>     * from terminating.  In effect, daemon threads will be terminated
>     * automatically by the OS when the process exits.
>     *
>     * Returns:
>     *  true if this is a daemon thread.
>     */
>    final @property bool isDaemon();
> 
> I'm confused... shouldn't daemon threads die when the main thread dies (which effectively exits the process)?

Yes, but remember that the main thread doesn't die the moment the app's main() function returns.  There's some runtime shutdown code that's run first.  See druntime/rt/dmain2.d.


More information about the Digitalmars-d-learn mailing list