Why does blocked IO in another thread prevent CreateWindowEx() from returning

I have a very simple Windows console application that first creates a thread to process input on stdin. It uses CreateThread() in main() to create the thread, and the first thing the thread does is call getchar() and block, waiting.

Then main() registers a window class using RegisterClass() and calls CreateWindowEx() to create an invisible message window.

BUT 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?

-------------Problems Reply------------

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 THREAD_ATTACH callback).

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 CreateThread).

Category:windows Views:236 Time:2016-06-04

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.160 (s). 11 q(s)