C++ WInApi thread - c++

on button "start" I doing thread
HANDLE hThread1;
case butStart:
hThread1=CreateThread(NULL, 0, func_pressF1, NULL, NULL, NULL);
break;
case butStop:
//code
break;
how can I free thread on button stop? I think with this functions can help
VOID WINAPI ExitThread(
__in DWORD dwExitCode
);
BOOL WINAPI GetExitCodeThread(
__in HANDLE hThread,
__out LPDWORD lpExitCode
);
but I don't know what I must write here __out LPDWORD lpExitCode.
Maybe someone can write code for my example

You should signal your thread to exit using some mechanism such as an event. After that the main thread should join the thread and then acquire the exit code (if needed). You should never force a thread to exit since resources might not get freed and mutexes might deadlock (if owned by the thread), for example.

Try WaitForSingleObject to wait until the thread completes, GetExitCodeThread to get the exit code (or just use a global variable), then CloseHandle to free the handle.
LPDWORD is just the address (a pointer) of a DWORD variable. Call like:
DWORD exit_code;
if (!GetExitCodeThread(hThread1, &exit_code)) // handle failure

__out LPDWORD lpExitCode means that you are providing a pointer to a DWORD in which the function will place the exit code for you, like a second return-value!
DWORD ec;
GetExitCodeThread(hThread, &ec);

ExitThread must be called by the thread itself. You can use TerminateThread which takes a thread-id as an argument and kills another thread.

Related

Why Sleep() on Main function stop all threads?

Why does Sleep() stop all created threads? I want to create a thread but keep the Main function in sleep until the thread finishes.
bool _finished = false;
void testcount(void *p){
int i = 0;
while(i<=30){
i++;
std::cout<<i<<"\n";
Sleep(1000);
}
_finished = true;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved){
HANDLE test = NULL;
test = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)testcount, NULL, NULL, NULL);
if(test)
std::cout<<"test thread created";
CloseHandle(test);
while(!_finished)
Sleep(1000);
return true;
}
I am trying it now like this, but the program just never finishes, because while with Sleep stops the thread. I don't want to return anything on Main while thread not finished. Any solution?
Calls to DllMain are serialised by Win32.
All new threads start by calling DllMain (with thread attach flag), and the call the method passed to CreateThread.
Therefore your thread is waiting to call DllMain, which cannot happen until your first thread leaves DllMain.
As commenter John Sheridan notes Raymond Chen's blog post from 2007 is a really good explanation.
PS. for correct C/C++ library initialisation you should be using _beginthread or _beginthreadex rather than CreateThread directly.
The new thread is blocked because your main thread does not leave DllMain, as described in Richard's answer.
Your code also contains a data race and has undefined behavior even after this deadlock is fixed. The new thread writes to _finished, the main thread reads from _finished, concurrently. You could try to use std::atomic<bool> instead of bool to fix this, assuming availability of C++11, or you could use Win32 primitives for thread synchronization.
Changes for standard solution using std::atomic<bool>:
#include <atomic>
std::atomic<bool> finished_{false};
// Rest remains the same

Is it safe to call std::thread::join function under Win32 DLL_PROCESS_DETACH? [duplicate]

I've stumbled upon an unexpected behavior of Windows thread mechanism when DLL is unloaded. A have a pack of worker thread objects and I'm trying to finish them graciously when DLL is unloaded (via DllMain DLL_PROCESS_DETACH). The code is very simple (I do send an event to finish the thread's wait loop):
WaitForSingleObject( ThrHandle, INFINITE );
CloseHandle( ThrHandle );
Yet the WaitForSingleObject hangs the whole thing. It works fine if I perform it before DLL is unloaded. How this behavior can be fixed?
You can't wait for a thread to exit in DllMain(). Unless the thread had already exited by the time the DLL_PROCESS_DETACH was received, doing so will always deadlock. This is the expected behaviour.
The reason for this is that calls to DllMain() are serialized, via the loader lock. When ExitThread() is called, it claims the loader lock so that it can call DllMain() with DLL_THREAD_DETACH. Until that call has finished, the thread is still running.
So DllMain is waiting for the thread to exit, and the thread is waiting for DllMain to exit, a classic deadlock situation.
See also Dynamic-Link Library Best Practices on MSDN.
The solution is to add a new function to your DLL for the application to call before unloading the DLL. As you have noted, your code already works perfectly well when called explicitly.
In the case where backwards compatibility requirements make adding such a function impossible, and if you must have the worker threads, consider splitting your DLL into two parts, one of which is dynamically loaded by the other. The dynamically loaded part would contain (at a minimum) all of the code needed by the worker threads.
When the DLL that was loaded by the application itself receives DLL_PROCESS_DETACH, you just set the event to signal the threads to exit and then return immediately. One of the threads would have to be designated to wait for all the others and then free the second DLL, which you can do safely using FreeLibraryAndExitThread().
(Depending on the circumstances, and in particular if worker threads are exiting and/or new ones being created as part of regular operations, you may need to be very careful to avoid race conditions and/or deadlocks; this would likely be simpler if you used a thread pool and callbacks rather than creating worker threads manually.)
In the special case where the threads do not need to use any but the very simplest Windows APIs, it might be possible to use a thread pool and work callbacks to avoid the need for a second DLL. Once the callbacks have exited, which you can check using WaitForThreadpoolWorkCallbacks(), it is safe for the library to be unloaded - you do not need to wait for the threads themselves to exit.
The catch here is that the callbacks must avoid any Windows APIs that might take the loader lock. It is not documented which API calls are safe in this respect, and it varies between different versions of Windows. If you are calling anything more complicated than SetEvent or WriteFile, say, or if you are using a library rather than native Windows API functions, you must not use this approach.
I have such problem when I try to inject code into another desktop process, WaitForSingleObject will cause the deadlock inside my thread. I solved the issue by trapping the window's default message procedure, hope it helps for others.
#define WM_INSIDER (WM_USER + 2021)
WNDPROC prev_proc = nullptr;
HWND FindTopWindow(DWORD pid)
{
struct Find { HWND win; DWORD pid; } find = { nullptr, pid };
EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL {
auto p = (Find*)(lParam);
DWORD id;
if (GetWindowThreadProcessId(hwnd, &id) && id == p->pid) {
// done
p->win = hwnd;
return FALSE;
}
// continue
return TRUE;
}, (LPARAM)&find);
return find.win;
}
// thread entry
int insider(void *)
{
// do whatever you want as a normal thread
return (0);
}
LRESULT CALLBACK insider_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
HANDLE t;
switch (uMsg) {
case WM_INSIDER:
t = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)insider, 0, 0, NULL);
CloseHandle(t);
break;
}
return CallWindowProc(prev_proc, hwnd, uMsg, wParam, lParam);
}
void setup() {
auto pid = GetCurrentProcessId();
auto win = FindTopWindow(pid);
prev_proc = (WNDPROC)SetWindowLongPtr(win, GWL_WNDPROC, (LONG_PTR)&insider_proc);
// signal to create thread later
PostMessage(win, WM_INSIDER, 0, 0);
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
setup();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}

Windows: WaitForSingleObject crashes when thread returns 0

I am having a strange behavior: WaitForSingleObject seems to crash when I return 0 from my thread, but if I call "ExitThread(0)" then it does not.
void waitForThread(DWORD &threadId)
{
HANDLE hThread = OpenThread(SYNCHRONIZE,
FALSE,
threadId);
if (hThread == NULL) return;
WaitForSingleObject(hThread, INFINITE); // Crashes here (not even returning)
CloseHandle(hThread);
}
According to the documentation:
ExitThread is the preferred method of exiting a thread in C code. However, in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed. Therefore, in C++ code, you should return from your thread function.
This does not make sense to me. I would think that "return 0" in my function with the signature:
DWORD WINAPI foo(LPVOID arg);
would be fine. For completeness, the thread is created using CreateThread, as such:
DWORD threadId;
HANDLE pth = CreateThread(NULL, // Default security attributes
0, // Default stack size
foo, // Thread name
arg, // Argument to thread
0, // Default creation flag
&threadId); // Returns thread ID
Does anyone know why the return statement would crash "WaitForSingleObject" please? I have put print statement before and after WaitForSingleObject, and one when the thread exists, and the behavior I see is: "Before WaitForSingleObject", "Thread finishes", Crash. Does anyone understand this behavior please?

Return value for a hooked function

I've been hooking some functions in order to make a protection for my app, I'm using Detours (CDetour), I'm hooking CreateThread, my hook function must be exact as the original one.
HANDLE WINAPI CreateThreadHook( LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID
lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId )
{
//do hooking stuff here
}
The hook works fine, the problem is that according to msdn If the function succeeds, the return value is a handle to the new thread. But since the function is hooked, the return value will be whatever I return, changing the hooked function to void or another type will only make the call have no return value, mostly leading to a crash. How can I return the value that should be returned by the original function?

Create thread is not accepting the member function

I am trying to create a class for network programming. This will create a general purpose socket with thread.
But when I tried to crete the thread using createthread(). The third argument is producing errors. And from the net I came to know that I can't use the member functions as an argument to the createthread().
Is there any thing by which I can achieve this?
The easiest way to handle this is to create a "stub" function which calls back into your class.
UINT tid
HANDLE hThread = CreateThread(NULL, 0, myThreadStub, this, 0, &tid);
....
unsigned long WINAPI myThreadStub(void *ptr)
{
if (!ptr) return -1;
return ((MyClass*)ptr)->ThreadMain();
}
CreateThread() allows you to pass an argument to the thread function (parameter 4 of the CreateThread() call). You can use this to pass a pointer to your class. You can then have the thread stub cast that pointer back into the proper type and then call a member function. You can even have "myThreadStub" be a static member of "MyClass", allowing it
to access private members and data.
If you have boost installed, you may be able to use boost::bind to do this without creating a stub function. I've never tried that on windows, so I can't say for sure it would work (because the callback function must be a WINAPI call) but if it does work it would look something like:
HANDLE hThread = CreateThread(NULL, 0, boost::bind(&MyClass::ThreadFunction, this), NULL, 0, &tid);
Where thread function is a non-static member function which takes a single void * argument.
There's an easy way to solve the problem.
Take a look at ThreadProc callback function:
DWORD WINAPI ThreadProc(
__in LPVOID lpParameter
);
And now at CreateThread function:
HANDLE WINAPI CreateThread(
__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
__in SIZE_T dwStackSize,
__in LPTHREAD_START_ROUTINE lpStartAddress,
__in_opt LPVOID lpParameter,
__in DWORD dwCreationFlags,
__out_opt LPDWORD lpThreadId
);
Use a static method as thread procedure, but call it from a member method, and pass the object pointer to it:
#include <windows.h>
class MyClass {
public:
void CreateThreadForObject() {
LPSECURITY_ATTRIBUTES security_attributes = 0;
SIZE_T stack_size = 0;
LPTHREAD_START_ROUTINE start_routine = &MyClass::ThreadProcForObject;
LPVOID param = this;
DWORD creation_flags = 0;
LPDWORD thread_id = 0;
CreateThread(security_attributes, stack_size, start_routine, param,
creation_flags, thread_id);
}
private:
static DWORD WINAPI ThreadProcForObject(LPVOID param) {
MyClass* instance = reinterpret_cast<MyClass*>(param);
if (!instance) return 1;
// ...
return 0;
}
};
Sorry, I just don't have enough time to write a good example. But I think you understand the way.
At lost I got it, the very fact is, in CreateThread if you pass the socket then there is no trouble. Because CreateThread is taking care of that socket. But if you pass as an object which is having that socket, then CreateThread is not taking care of the socket, and it is ends up in invalid socket in the new thread.
The successed code below
SOCKET s=socket(....);
bind(s,...);
listen(s,...);
SOCKET temp=accept(s,(sockaddr *)&addrNew,&size);
DWORD threadId;
HANDLE thread=CreateThread(NULL,0,&MyThreadFunction,(LPVOID)(temp),0,&threadId);