I'm trying to understand what the difference is between CreateThread and _beginthreadex and why calling DisableThreadLibraryCalls only prevents threads installed with _beginthreadex from executing.
I have a project which is a DLL, an old DLL, this is a win32 dll and I am tasked with porting it to win64. One thing that tripped me up was a call in DLLMain to DisableThreadLibraryCalls.
My threads were installed with _beginthreadex, the body of the threads was never being executed cause of the call to DisableThreadLibraryCalls. Once I removed this, the threads were working correctly.
Now I've found that other threads in the same DLL are started with CreateThread, I then thought was the call to DisableThreadLibraryCalls there to prevent these threads from executing so I put it back and found that the threads created with CreateThread are executed regardless of if DisableThreadLibraryCalls is present or not but threads created with _beginthreadex are disabled.
Why? I can't find anything on:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682579(v=vs.85).aspx
That describes why this is happening.
CreateThread() is a Windows native API for creating threads while _beginthread() and _beginthreadex() are part of C runtime library and are intended to make it easier to manage thread creation, but they still internally have to call CreateThread().
Your own answer is wrong because there is no explicit checking for enable/disable involved in C runtime.
Instead, C runtime library uses DLL_THREAD_ATTACH and DLL_THREAD_DETACH callbacks to manage thread local storage so it should not be surprising that disabling those callbacks by calling DisableThreadLibraryCalls() is preventing C runtime thread management functions from working correctly.
I have found references online that state that _beginthread and _beginthreadex interally call CreateThread so perhaps the checking disable/enable status is only performed in the top level routines which does echo my findings and to me suggests missing logic in CreateThread.
DisableThreadLibaryCalls has no effect on threads created with CreateThread directly.
Related
I have multithreaded application. Now, I have written one function in Windows DLL.
I am calling this DLL function from thread function (called by multiple threads) which is in my application.
So, my question is, does this DLL function also executes on same calling thread?
(And no need to handle multithreading separately in DLL)
Yes, the DLL function will execute on the same thread as the caller. There is no need to handle multithreading separately in the DLL.
I'm getting some DLL_THREAD_ATTACH notifications in my COM DLL, but none from the app pool worker threads, from which my COM DLL is actually invoked.
Subsequently, calls to the DLL initiated from IIS arrive on threads for which DLL_THREAD_ATTACH was never called.
Only the first thread of the app pool is notified when the DLL is attached to dllhost.exe (via DLL_PROCESS_ATTACH).
Is this a defect or a feature, and is there any workaround?
DLL_THREAD_ATTACH is often misunderstood. You don't give enough information, but it is likely that your problem is due to this :
From the MSDN documentation, emphasis mine :
DLL_THREAD_ATTACH | The current process is creating a new thread.
On the same page :
There are cases in which the entry-point function is called for a terminating thread even if the entry-point function was never called with DLL_THREAD_ATTACH for the thread:
The thread was the initial thread in the process, so the system called the entry-point function with the DLL_PROCESS_ATTACH value.
The thread was already running when a call to the LoadLibrary function was made, so the system never called the entry-point function for it.
To work around this, you can either manually enumerate every thread of a process when DLL_PROCESS_ATTACH. You can also do a first time init when your DLL functions are invoked on a new thread. Obviously, you can also create the threads AFTER the DLL is loaded, if it is possible.
I wanted to make sure i fully understand those API functions. If I have an application and a dll where i created a thread. I load this dll inside the application with LoadLibrary function. Does it mean that this dll thread is now a thread of that application?
P.S The thread in the dll created via exported function if that matters.
Thanks.
Understand that threads are an element of an executing process - there's no real notion of a DLL "owning" a thread. The code that starts the thread may well have originated from a function call in code contained in a DLL, but the process that loaded the library is the one that owns the thread. Loading the library merely makes the code in that library available to the calling process dynamically (at runtime).
Is it okay to register WSACleanup through atExit function ? We have several applications that can terminate at different points in the code so we would like to avoid putting WSACleanup everywhere throughought the code. Curently we call WSAStartup / WSACleanup through DllMain since we have a dll that is used by all these applications. However, Microsoft strictly advices against the use of WSAStartup / WSACleanup via DllMain since this can cause deadlocks. We can move WSAStarup out of DllMain and call this at one point in the code for all applications before they access the Windows sockets library. And, as soon as we call WSAStartup, we would like to use the atExit function to register a call to WSACleanup. Does anyone have any experiences with this approach ? Thanks!
If you have a multi-threaded app and some of the threads are still connected, the applications at the other end may not like the way the connection is terminated. So it is preferable to close down all communication in an ordered way before main() terminates, and when you have done that, you can just as well call WSACleanup.
I agree that the RAII approach is favourable.
However a word of warning: atExit mixed with dlls and handles is broken on windows. Unfortunately this effects RAII too as this is implemented with atExit handlers by the c++ runtime.
The order that atexit handlers are called on windows:
somewhere exit is called or main() goes out of scope
atexit handlers defined in the process are called.
all handles are destroyed.
atexit handlers defined in dlls are called.
It doesn't matter if atexit handlers in dlls are registered before handlers in the process the process handlers are called first and the handles are destroyed before the dll handlers are called. This results in win32 exceptions, when the clean up code is called as all the handles owned by dlls are no longer valid.
This effects code that holds handles to threads, mutexs, files, sockets etc. If they are allocated in a dll then they must be cleaned up before exit is called or not at all.
By the way I am not anti window, if I am wrong or anyone knows any way around this I would love to know as this causes me untold pain in application clean up. I figured this out be debugging exit handling in the c++ runtime, after getting win32 exceptions when applications exit.
I had to remove all calls to exit from my code. I now ensured that no static data in a dll controls a handle. All static handles are controlled by objects that are destructed when main goes out of scope.
Well I think atExit should not be used. You should follow RAII principle of wrapping of initialization and destruction of socket library in a class.
I tend to use POSIX Threads, when programming in C, under Linux.
Without MFC
Question:
How would I then create threads in VC++?
Find more information on threads under win32?
Edit:
Brief illustrations
I LOVE stackoverflow - best resource for students!
Regards
if you're looking for a platform-independent method, use boost
there's also beginthread() and beginthreadex() functions. Both seem to be supplemental to Win32 API, in a sense that in many use cases, you still need to call some Win32 functions (such as CloseHandle for beginthreadex). So, if you don't care that much about platform compatibility, you might as well cut the foreplay and use CreateThread().
Win32 thread handling is documented here: http://msdn.microsoft.com/en-us/library/ms684852(VS.85).aspx
[edit1] example:
DWORD WINAPI MyThreadProc( void* pContext )
{
return 0;
}
HANDLE h = CreateThread( NULL, 0, MyThreadProc, this, 0L, NULL );
WaitForSingleObject(h, TIME); // wait for thread to exit, TIME is a DWORD in milliseconds
[edit2] CRT & CreateThread():
per MSDN:
A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; this requires the use of the multi-threaded version of the CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the process in low-memory conditions.
You should not use the raw Win32 CreateThread() API.
Use the C runtime's _beginthreadex() so the runtime has an opportunity to set up its own thread support.
You can use either the CRT function _beginthreadex() or the Windows API function CreateThread(). _beginthreadex() is required for early versions of VC++ that had a CRT that didn't lazily initialize thread-local storage. CreateThread() is fine in at least VS2005 and up.
You probably want to take a look at the CreateThread() function.
Use _beginthread() or _beginthreadex() to create a new thread. Do NOT use the Win32 function CreateThread() -- it does not properly initialize the multithreaded aspects of the C runtime. See also this question.
Some good books on the subject are Petzold's Programming Windows and Richter's Programming Applications for Windows. In particular, the latter goes into server side programming such as thread and synchronisation API's in a lot of depth.
EDIT: For code snippets, Google is your friend. For example This article has some minimal thread examples.
There is also the _beginthread() function you can look up. It differs a bit from CreateThread(), you should be aware of the differences before choosing one.