Proper way to exit with specific exit code?
H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Sep 18 14:25:29 UTC 2020
On Fri, Sep 18, 2020 at 08:20:59AM +0000, IGotD- via Digitalmars-d-learn wrote:
> On Friday, 18 September 2020 at 05:02:21 UTC, H. S. Teoh wrote:
> > That's the obvious solution, except that actually implementing it is not
> > so simple. When you have multiple threads listening for each other
> > and/or doing work, there is no 100% guaranteed way of cleanly shutting
> > all of them down at the same time. You can't just clean up the calling
> > thread and leave the others running, because the other threads might
> > hold references to your data, etc.. But there's no universal protocol
> > for shutting down the other threads too -- they could be in a busy loop
> > with some long-running computation, or they may not be checking for
> > thread messages, or they could be in a server loop that is designed to
> > keep running, etc.. It's one of those annoying things that reduce to
> > the halting problem in the general case.
> I think a pragmatic solution is just to mutex protect the D exit
> function in case several threads tries to use simultaneously. Then if
> more threads call exit, it will do nothing as the first one that
> called exit actually do the tear down.
That does not solve the problem. If thread 1 calls exit but thread 2 is
still running and processing data via a shared reference with thread 1's
data, you absolutely do not want to run dtors and tear-down code until
thread 2 is done, otherwise you have a problem.
OTOH, waiting for thread 2 to finish first comes with its own problems:
what if thread 2 never calls exit? Then no cleanup will be done, which
may not be desirable either (maybe you had thread 1 call exit because
you wanted to release unused resources).
> Also, it should be responsibility of the program to ensure that its
> tear down code runs before calling the D exit function. That's the
> only way I can think of because waiting for all other threads to
> release their resources and exit isn't really realistic either as that
> might do that the program exit never happens. Whatever you do you, you
> have to resort to some "manual" solution".
If you're prepared to do manual teardown, then you do not need a
D-specific exit function. Just call core.sys.stdc.stdlib.exit and call
it a day. :-)
Never trust an operating system you don't have source for! -- Martin Schulze
More information about the Digitalmars-d-learn