I have a very simple Windows console application that first creates a thread to process input on stdin. It uses
main() to create the thread, and the first thing the thread does is call
getchar() and block, waiting.
main() registers a window class using
RegisterClass() and calls
CreateWindowEx() to create an invisible message window.
CreateWindowEx() never returns.
If I remove the
getchar() in the thread and replace it with
while (1) Sleep(1000);, everything works.
If I add
Sleep(1000); to the start of the thread function, the
CreateWindowEx() call succeeds but then the I/O in the thread stops working (
getchar() doesn't return).
Why is the blocked 2nd thread interfering with the first?
The C runtime library doesn't officially support being called from a thread spawned with
CreateThread. You're supposed to use the CRT wrapper functions such as
_beginthreadex, which properly configure CRT thread-local state on the new thread.
In practice, the CRT goes to great lengths to make things work even if you break that rule, but the details depend on whether you're statically or dynamically linking with the CRT (since that affects whether there's a
Try doing it "right" by only making CRT calls on threads started with
_beginthreadex. (One way is to keep using
CreateThread and then use
ReadConsole in the worker thread instead of
getchar, the other is to use
_beginthreadex instead of