Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread creation, the CRT and DLL's how is it meant to be done?

Tags:

c++

windows

dll

crt

So I understand that CreateThread and the CRT can result in memory leaks, signal doesn't work, and one should use the _beginthread or _beginthreadex functions.

That is all very well when writing an application, but what about those that are writing dll's and such for other applications (be it a plain c dll, com objects, plugins, etc). There is no way to guarantee how a thread calling into a DLL was created, even if they used __beginthread(ex) its a pretty likely bet they have a different CRT implementation\version.

So what exactly is it that programmers are expected to do? Not use the CRT? Spawn an internal thread and offload all work to that (without using the CRT with the calling thread)? Some trick with DllMain and the attach/detach stuff to correctly setup and shutdown all threads regardless of how they are created?

like image 846
Fire Lancer Avatar asked Aug 04 '12 12:08

Fire Lancer


1 Answers

CreateThread and the CRT can result in memory leaks

No, that's a misunderstanding that's incredibly difficult to get rid of for some reason. Using _beginthread() was necessary back in the previous century, VS6 was the last version of VS that had a CRT that still required it.

That's been fixed, in no small part to deal with the support for the thread pool added to Windows 2000. Clearly you can't do anything in the CRT to deal with them, those threads are started by the OS itself. The implementation is pretty straight-forward. Wherever the CRT needs a thread-local variable, like the one needed by strtok(), it first checks if TLS storage was already allocated for the thread. If not, it allocates it on-the-fly.

Just use CreateThread() without fear, implicit of course with the assumption that you no longer use a 14 year old compiler.

like image 69
Hans Passant Avatar answered Oct 04 '22 08:10

Hans Passant