On Wednesday 07 October 2026 12:58:14 Kirill Makurin wrote:
> Pali Rohár <[email protected]> wrote:
> 
> > On Wednesday 07 October 2026 12:37:09 Kirill Makurin wrote:
> >> A thread that was detached with `thrd_detach` cannot be joined with 
> >> `thrd_join` or vice versa; doing so is undefined behavior. Well, in case 
> >> of MSVC implementation, it seems like it will actually work.
> >
> > That is only for _successfully_ detached. Because of NULL handles
> > returned by thrd_current(), the thrd_detach call fails and returns
> > error. So if the thrd_detach(thrd_current()) fails then the parent
> > thread could still successfully call thrd_join(child_thrd) and here the
> > child_thrd contains the valid non-NULL handle (so it will success).
> 
> After successful call to `thrd_detach`, handle in `thrd_t` structure returned 
> by `thed_current` is set to `NULL`, yes. However, any existing instance of 
> `thrd_t` for such thread still contains original thread handle (e.g. from the 
> original `thrd_create` call), which means call to `thrd_join` will not return 
> error.

That original thread handle is invalidated (closed) by the thrd_detach call.
So trying to use it after that will cause WinAPI error invalid handle.
The thrd_join() will therefore return an error.

See: https://godbolt.org/z/Ex9KKEM71

The example is throwing SEH 3221225480 (0xC0000008 == STATUS_INVALID_HANDLE).
If you comment the #if 1 part for the thrd_join() then it the example
will not throw SEH. I guess that runtime is configured to throw SEH when
invalid handle is used (instead of just returning error via SetLastError()).

> > Idea for thrd_detach(thrd_current()) implementation:
> > - thrd_create() will additionally store the handle of child thread to
> >   the TLS storage of the child thread (ideally using the shared memory
> >   trick, so even static linking of same thrd_create function multiple
> >   times would work)
> > - thrd_detach() will check if the thread HANDLE (from passed pair) is
> >   NULL and if yes, it will retrieve the real HANDLE from TLS storage of
> >   the thread identified by threadid (from passed pair)
> 
> - Kirill Makurin


_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public

Reply via email to