I have this program.cpp :
#include <stdio.h>
#include <windows.h>
DWORD WINAPI separateThread(LPVOID)
{ printf("thread waiting user input\n");
char str[128]; fgets(str, 128, stdin);
printf("fgets END ...");
}
int main()
{
printf("program start autokill after 5sec\n");
DWORD tid; HANDLE tha =CreateThread(0,0, separateThread, 0,0,&tid);
Sleep(5000);
// XXXXXXXX what to put here to Kill fgets-callin-thread ???????????
}
compiled in linux with:
i686-w64-mingw32-gcc program.cpp
and running it with:
wine a.exe
... and I want it to be ended itself, WITHOUT ANY USER INPUT. But there is always err:ntdll:RtlpWaitForCriticalSection witch blocks everything.
What should I put in XXXXX place?
Solutions that not helps: TerminateThread(tha, 0), ExitProcess(0), reopen(stdin), fclose(stdin) ... Implementing own 'my_gets' function by kbhit-getch combination is good solution for xp, win7 and win8 target, but kbhit in WINE does not work.
Terminating threads is almost never safe. It may leave things in inconsistent, broken state.
Consider a thread that was halfway through memory allocation for example. The thread locked the mutex used to synchronize access to the heap. If abruptly terminated, the thread won't realease the lock. Any subsequent attempt to allocate memory will hang.
One possible solution is to terminate the entire process (terminateprocess function). It will result in all threads being terminated and the process exiting without performing any cleanup. It means for instance that stdout won't be flushed, registered atexit handlers won't run as well as any C++ destructors. However OS-level resources like open files and memory will be released properly.
There is also exitprocess to perform orderly process shutdown. It performs the cleanup but it suffers from the corrupted global state due to abrupt thread termination (consider free() being called during cleanup, it hangs if the heap was corrupted).
A sidenote. Use _beginthread instead of CreateThread in order to initialise c runtime library properly in the new thread.