LIU Hao wrote:

> 在 2026-8-28 11:23, Kirill Makurin 写道:
>> Unlike `CreateThread`, functions `_beginthread[ex]` also initialize CRT's 
>> per-thread state. Documentation[1] for `CreateThread` explicitly tells that 
>> if a thread calls any CRT function, it must instead call `_beginthread[ex]`. 
>> Pali can tell more about it, as he looked at it more closely.
>
> The thread-local CRT state is initialized on demand; see
> https://devblogs.microsoft.com/oldnewthing/20171115-00/?p=97405.
>
> (Consider: what happens if a thread which was created by DLL X which was 
> linked MSVCR80.DLL later calls
> into DLL Y which was linked against MSVCR90.DLL?)

Hopefully such scenarios are not common for new applications nowadays, with 
system msvcrt.dll being an exception.

For example, my posix32 library contains very crt-specific locale-related code, 
and in case if it is linked against a CRT that is different from one the 
application/DLL is linked to, it will result in very inconsistent behavior; 
e.g. it will set thread/global locale for the wrong CRT.

> The per-thread state is freed in the entry point callback of a CRT DLL, which 
> explains why there may be a
> resource leak if the CRT is linked statically; but that doesn't apply to 
> mingw-w64.

Yes, I also have impression that using `_beginthreadex` should really only make 
difference for static CRT, which is only supported with MSVC. It is worth to 
mention that this is a valid build configuration when it comes to winpthreads.

Some time ago me and Pali were discussing some stuff, and I asked if we can 
simply use `CreateThread` with mingw-w64 build of winpthreads, and he suggested 
we stick with `_beginthreadex`. I hope he can share more details.

- Kirill Makurin

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

Reply via email to