Creating Windows and Threading - C++ - c++

When a new window is created using CreateEx does its code execute in its own thread or that of its parent (i.e. the thread in which the its instantiating code was executed)? Thanks.

The window doesn't actually run any code on its own, all the code is called from the message loop which is part of your own code. You can run into huge issues trying to interact with the Windows UI with multiple threads, so you should always respond to the messages within a single thread.

CreateWindowEx() does not create a new thread. If you want a new thread you have to call
either _beginthreadex() (usually preferred) or CreateThread().
In case you're wondering, _beginthreadex() is preferred over CreateThread() because the former initializes parts of the CRT that the latter does not.

Windows have thread affinity – see Raymond Chen's article on this matter.

No, create window dont start new thread

Cross-thread GUI stuff usually ends in disaster. The windows libraries actively discourage it by throwing exceptions.
Even if it was allowed, CreateWindowEx could not do this by default because it would be making some very big assumptions about your code (locks, thread safety, etc); and most Windows development is probably still essentially single threaded.

Related

Is it correct to use std::async for background tasks inside an internal thread (not from main process's thread)

I would like to have your opinion for this general technical concept. (I am working on microsoft windows OS)
There is a Process, this process creates multiple threads for different tasks.
Main process: it is a windows service written by C# code.
There are several threads that are create inside the main process: Thread_01, Thread_02, ...
Inside Thread_01: There is a Wrapper dll written in managed C++ to consume DLL_01. (DLL_01 is a dll written by me in native C++ code, that provides some APIs: Add, Remove, Connect)
Add and Remove can run very fast, but Connect may take more than 10 seconds and blocks the caller until it finishes.
I am thinking to use std::async to do the Connect function code, and send the result through a callback to the caller (main process).
Is it a good approach? I heard we cannot create or it is better not to create any thread inside inner threads, is it true? If so, how about std::async ?
Any recommendation is appreciated.
Thanks in advance,
None of what you describe makes the use of threads inacceptable for your code.
As usual, threads have issues that need to be cared for:
Data races due to access to shared data.
Problems of ownership of resources is now not just "Who own what?" but "Who and when owns what?".
When a thread is blocked and you want to abort this operation, how do you cancel it without causing issues down the line? In your case, you must avoid calling the callback, when the receiver doesn't exist any more.
Concerning your approach of using a callback, consider std::future<> instead. This takes care of a few of the issues above, though some are only shifted to the caller instead.

Should I use thread in my library?

I am implementing a function in library which takes a while (up to a minute). It initialize a device. Now generally any long function should run in its own thread and report to main thread when it completes but I am not sure since this function is in library.
My dilemma is this, even if I implement this in a separate thread, another thread in the application has to wait on it. If so why not let the application run this function in that thread anyways?
I could pass queue or mailbox to the library function but I would prefer a simpler mechanism where the library can be used in VB, VC, C# or other windows platforms.
Alternatively I could pass HWND of the window and the library function can post message to it when it completes instead of signaling any event. That seems like most practical approach if I have to implement the function in its own thread. Is this reasonable?
Currently my function prototype is:
void InitDevice(HANDLE hWait)
When initialization is complete than I signal bWait. This works fine but I am not convinced I should use thread anyways when another secondary thread will have to wait on InitDevice. Should I pass HWNDinstead? That way the message will be posted to the primary thread and it will make better sense with multithreading.
In general, when I write library code, I normally try to stay away from creating threads unless it's really necessary. By creating a thread, you're forcing a particular threading model on the application. Perhaps they wish to use it from a very simplistic command-line tool where a single thread is fine. Or they could use it from a GUI tool where things must be multi-threaded.
So, instead, just give the library user understanding that a function call is a long-term blocking call, some callback mechanism to monitor the progress, and finally a way to immediately halt the operation which could be used by a multi-threaded application.
What you do want to claim is being thread safe. Use mutexes to protect data items if there are other functions they can call to affect the operation of the blocking function.

MFC: accessing GUI from another thread?

So generally only the main thread should access the GUI in a MFC application.
However is that a law or just recommended? If I make sure, via critical sections, that only one thread accesses a certain object in the GUI, is it ok then? Or is it a problem if the MAIN thread accesses one part of the GUI while another thread access one. Even if those 2 objects don't affect each other?
The reason I ask is because this simplifies my rewrite of the application a lot if I can access the GUI from another thread.
Don't do it. You'll live in a world of ASSERTs and weird behaviour if you do. The GUI works through a system of Windows messages which are 'pumped' on the main thread. If you start modifying the UI in another thread you'll have situations where your operation causes other UI messages, which will be handled by the main thread potentially at the same time you're still trying to access the UI on another thread.
MFC programming is hard enough without trying to handle this sort of thing. Instead use PostMessage to put the UI related handling onto the main thread.
I used to think its almost forbidden to access GUI from a worker thread in MFC and is a recipe for disaster. But recently I learned this is not that hard rule if you know what you are doing, you can use worker threads to access GUI. In the Win32 Multithreaded Book the provides an example of a 'self animated control' which is completely drawn in a worker thread.
If I remember correctly the author pretty much said the same thing you said, if you critical sections at the right places you can make accessing GUI thread safe. The reason MFC doesn't do it by itself is for performance reasons.

Win32 API deadlocks while using different threads

I am experience deadlock while trying to use WIN32 API from additional thread. The additional thread is needed in my application to improve Frame Rate. It actually helps, however, I get deadlocks in almost all of the system functions:
::ShowWindow
::MoveWindow
::UpdateWindow
I know that ShowWindow() for example, may be replaced with ShowWindowAsync() and it does solves the problem, however, there are no such alternatives in MoveWindow() and UpdateWindow().
Did someone experienced those problems, what is solution?
Thanks!
The term "deadlock" describes a very specific thing, two threads waiting for access to a resource that is locked by the other. There is no indication that this is what is happening in your case (or is there?), so what exactly is it that you are experiencing? Also, what exactly is it that you want to achieve with multithreading?
In any case, keep the UI in a single thread, use SendMessage() & Co to notify that thread of any events occurring in background threads. Alternatively, you can also use a timer to poll for certain state changes. That way, you are on the safe side and your application shouldn't lock up (at least not because of using the UI from different threads).
To be a bit more precise, you have to keep the message loop for a window and all its child windows in a single thread. You can create multiple windows and handle each of them from their own thread, but don't mix calls. In practice, this distinction isn't important though, because few applications create multiple windows (and no, e.g. a message box or other dialogs don't count).
All the API functions that you refer to have in common that they send(!) some message to the target window. UpdateWindow is probably the most obvious, because it needs to send WM_PAINT. Notice also that it "sends" the message and doesn't post to the queue (for UpdateWindow, the MSDN documentation calls this out explicitly, for the others it may be less obvious).
Also notice that windows have thread affinity as alluded to in some of the comments. Among other things this means that messages to that window are only ever received/dispatched on one thread. If you send a message to a window of another thread, the operating system is left with the task to determine when it should dispatch that message (i.e. call the window procedure). This (dispatching incoming sent messages) only happens during certain API calls during which it can be assumed to be safe to invoke the window procedure with a random message. The relevant times are during GetMessage and PeekMessage*.
So if your window owning thread (also called UI thread) is pumping messages normally, incoming sent messages are also quickly dispatched. From your question it seems however, that your UI thread is currently busy. If the second thread then invokes one of said functions, then it will block until the first thread provides a chance to have the sent messages dispatched.
As others have said, it is usually a good idea to keep user interface code on one dedicated UI thread (although exceptions - as always - prove the rule). And it is definitely necessary (for a good user experience) to have window owning threads be responsive to messages at all times. If your UI thread also has to wait on some synchronization objects, you may find MsgWaitForMultipleObjects helpful.
*the list might not be complete.

How can I write cross platform c++ that handles signals?

This question is more for my personal curiosity than anything important. I'm trying to keep all my code compatible with at least Windows and Mac. So far I've learned that I should base my code on POSIX and that's just great but...
Windows doesn't have a sigaction function so signal is used? According to:
What is the difference between sigaction and signal? there are some problems with signal.
The signal() function does not block other signals from arriving while the current handler is executing; sigaction() can block other signals until the current handler returns.
The signal() function resets the signal action back to SIG_DFL (default) for almost all signals. This means that the signal() handler must reinstall itself as its first action. It also opens up a window of vulnerability between the time when the signal is detected and the handler is reinstalled during which if a second instance of the signal arrives, the default behaviour (usually terminate, sometimes with prejudice - aka core dump) occurs.
If two SIGINT's come quickly then the application will terminate with default behavior. Is there any way to fix this behavior? What other implications do these two issues have on a process that, for instance wants to block SIGINT? Are there any other issues that I'm likely to run across while using signal? How do I fix them?
You really don't want to deal with signal()'s at all.
You want "events".
Ideally, you'll find a framework that's portable to all the main environments you wish to target - that would determine your choice of "event" implementation.
Here's an interesting thread that might help:
Game Objects Talking To Each Other
PS:
The main difference between signal() and sigaction() is that sigaction() is "signal()" on steroids - more options, allows SA_RESTART, etc. I'd discourage using either one unless you really, really need to.