在 2026-10-7 21:15, Pali Rohár 写道:
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.
The issue is about this code:
#include <threads.h>
#include <stdio.h>
int
thread_fn(void* arg)
{
printf("thread_fn\n");
int err = thrd_detach(thrd_current());
printf("detached self: %d\n", err); // expected: zero
return 0;
}
int
main(void)
{
thrd_t thr;
int err = thrd_create(&thr, thread_fn, NULL);
if(err != thrd_success)
return 1;
thrd_sleep(&(struct timespec){ .tv_sec = 1 }, NULL);
err = thrd_join(thr, NULL);
printf("joined thread: %d\n", err); // expected: non-zero
}
With MSVC this gives:
thread_fn
detached self: 4
joined thread: 0
--
Best regards,
LIU Hao
OpenPGP_signature.asc
Description: OpenPGP digital signature
_______________________________________________ Mingw-w64-public mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/mingw-w64-public
