mutually dependent threads and ownership - c++

Background:
I have two GUI threads: Main and SendEmail in an MFC/Win32 application.
Normally, the main thread spawns the send email thread and continues to run. The send email thread tells the main thread's window to stay disabled and captures the mouse, and when it exits, it enables the main thread's window and releases the mouse.
This gives the user the work-flow of the main application is disabled while they're sending an email. The need to do this in a separate thread has to do with problems with MAPI and Outlook since 2010, where it would lock up the app if it was executed on the main thread.
However, if it so happens that the main application does exit while the send mail thread is still running, the process crashes (the send mail thread tries to enable the main thread's window which no longer exists...)
Goal:
To have the main thread wait for the send mail thread to terminate before terminating
Sticking point:
Currently, the email thread self-destructs (there is no memory management, since it calls delete on itself when its run method finishes). But I want the main thread to keep a reference to this thread so that it can wait on a live one at exit.
I cannot use a weak reference, I don't think, because the main thread really should wait on this thread object (threads are inherently waitable), so I don't want the object that represents this thread to self-destruct while the min thread holds it.
I can use a shared pointer - so that both the application and the running thread effectively keep the thread object alive... but then how to delete the application's copy of the thread object when the thread is finished? (I don't want the thread object to keep on existing for no purpose).
I could post a message from the email thread to the main app thread saying "I'm dying" so that the main thread immediately waits for the thread to terminate and then deletes its reference...
Any better ideas?

Related

Native C++ Asynchronous background thread with a return value, main thread can not be blocked

I'm struggling with the idea of background threads in C++.
When I start my application, a thread begins operating in the background for a while. When it is finished, I need to display a message box (whose content depends on the thread's result) and call a function, both on the main thread. While the background thread is running, the application must remain responsive to the user.
I looked at std::future, but that still requires me to either block the main thread or to have some sort of loop running in the main thread that checks the result periodically. But this loop would also have to run asynchronously, leading to the same issue again.
Can someone enlighten me?

How do I create multiple C++ threads without blocking the main thread using join()?

I have a simple TCP client/server in C++ and I am currently spawning a thread per connected user to handle messages, however I have run into a few issues and I'm not sure how to solve them as I am unfamiliar with the standard C++ threading.
When a client connects to the server, a thread is created for that client until they are disconnected using something like
clientThread = thread(processMessages);
clientThread.join();
This thread will persist for the lifetime of the client. As I have called join() on this thread, when client 2 connects while client 1 is still connected, it is blocked by the join() call.
Removing this join() call means that when a client disconnects, the thread is destroyed causing a terminate() error due to it being joinable.
How can I make this client thread just process in the background while the main thread can just continue and accept new connections?
Just showing how you can store created thread objects:
std::vector<std::thread> threads;
threads.emplace_back(processMessages);
...
for (auto & t : threads) t.join();
However, as others pointed out in comments, creating a thread for each new connection might not be the best approach.

How to stop and destroy thread from main thread (from which is created)

I need to create, run, stop thread and then again same process (reloading some new data and need to refresh and cannot use C++11 standard). I have created and run thread like from mine main thread
pthread_t p;
pthread_create(&p, NULL, calculation, some_pointer_to_object);
How to stop and destroy this thread from main thread ?
(pthread_exit is from current thread).
You need to use pthread_cancel().
The only clean way to do so is this: Set up a flag in the main thread, start the thread, poll the flag in your new thread and finish fast if it's set. Everything else but letting your new thread close itself down cleanly on request opens a boatload of cans of worms, and that's an understatement.

How does the message loop use threads?

I'm somewhat confused and wondering if I've been misinformed, in a separate post I was told "New threads are only created when you make them explicitly. C++ programs are by default single threaded." When I open my program that doesn't explicitly create new threads in ollydbg I noticed multiple times that there are often 2 threads running. I wanted to understand how the message loop works without stopping up execution, the explanation I got was very insufficient at explaining how it works.
Does the message loop create a new thread or does it take up the main thread? If it takes the main thread does it do so after everything else has been executed regardless of code order? If it doesn't do this but still takes up the main thread does it spawn a new thread so that the program can execute instead of getting stuck in the message loop?
EDIT: Solved most of my questions with experimentation. The message loop occupies the main thread and any code after the code:
while (GetMessage (&messages, NULL, 0, 0))
{
TranslateMessage(&messages);
DispatchMessage(&messages);
}
return messages.wParam;
Will not execute unless something special is done to cause it to execute because the program is stuck in the message loop. Putting an infinite loop in a window procedure that gets executed causes the program to crash. I still don't understand the mystery of the multiple threads when in olly to the degree I would prefer though.
Perhaps the place to start is to realize that "the message loop" isn't a thing as such; it's really just something that a thread does.
Threads in windows generally fall into one of two categories: those that own UI, and those that do background work (eg network operations).
A simple UI app typically has just one thread, which is a UI thread. For the UI to work, the thread needs to wait until there's some input to handle (mouse click, keyboard input, etc), handle the input (eg. update the state and redraw the window), and then go back to waiting for more input. This whole act of "wait for input, process it, repeat" is the message loop. (Also worth mentioning at this stage is the message queue: each thread has its own input queue which stores up the input messages for a thread; and the act of a thread "waiting for input" is really about checking if there's anything in the queue, and if not, waiting till there is.) In win32 speak, if a thread is actively processing input this way, it's also said to be "pumping messages".
A typical simple windows app's mainline code will first do basic initialization, create the main window, and then do the wait-for-input-and-process-it message loop. It does this usually until the user closes the main window, at which point the thread exits the loop, and carries on executing the code that comes afterwards, which is usually cleanup code.
A common architecture in windows apps is to have a main UI thread - usually this is the main thread - and it creates and owns all the UI, and has a message loop that dispatches messages for all of the UI that the thread created. If an app needs to do something that could potentially block, such as reading from a socket, a worker thread is often used for that purpose: you don't want the UI thread to block (eg. while waiting for input from a socket), as it wouldn't be processing input during that time and the UI would end up being unresponsive.
You could write an app that had more than one UI thread in it - and each thread that creates windows would then need its own message loop - but it's a fairly advanced technique and not all that useful for most basic apps.
The other threads you are seeing are likely some sort of helper threads that are created by Windows to do background tasks; and for the most part, you can ignore them. If you initialize COM, for example, windows may end up creating a worker thread to manage some COM internal stuff, and it may also create some invisible HWNDs too.
Typically the thread that starts the program only runs the message loop, taking up the main thread. Anything not part of handling messages or updating the UI is typically done by other threads. The additional thread that you see even if your application doesn't create any threads could be created by a library or the operating system. Windows will create threads inside your process to handle things like dispatching events to your message loop.

Windows Api Multi-threading Messages

I'm just curious as to to how to implement multi-threading without using a Windows API WaitFor* function that stops the program until the thread has returned. What's the point of using threads if they stop the main application from being resized or moved etc.?
Is there any form of windows messaging with threading, which will allow me to call my thread function and then return, and handle the return values of the thread when it finishes running?
If you want your UI thread to know when a task thread has finished it's task then you could have your task thread post a (custom - WM_USER and above) message to your main window (along with thread id plus the handle). And the window proc of the main window can know that a particular task thread has finished it's task. This way the UI thread does not have to wait actively (using WaitFor*) on the thread(s) object.
You can use MsgWaitForMultipleObjectsEx to wait for the thread to finish and also process messages at the same time.
Have a look at std::thread, boost::thread, just::thread, for multithreading in general for c++.
But about Windows messaging win32 and MFC, the MSDN states explicitely that it is not multithread, it is monothread. ( Undefined behaviour is to be expected if multithreading is used)
For asynchronous message emited in other thread than the main application window thread, you should use ::PostMessage(), that will insert message events in the monothread message pump of the mono threaded window.
WaitForSingleObject can be non-blocking, just pass zero timeout as second parameter:
// Check is thread has been finished
if(::WaitForSingleObject(threadHandle, 0) == WAIT_OBJECT_0)
{
// Process results
...
}
You will need to periodically check this condition, e.g. on timer or after processing any message in message loop.
Or you can use MsgWaitForMultipleObjectsEx. It will unblock and return when some message/input event occured in calling thread message queue.
As other answers mentioned there is another way - using Windows asynchronously posted message to signal that thread has done its work. This way has disadvantage - the working thread must know target window or thread to post message to. This dependency complicates design and raises issues about checking thread/window lifetime. To avoid it message broadcasting (PostMessage(HWND_BROADCAST,...))
can be used, but this is overkill for your case, I don't recommend it.