user4344762
user4344762

Reputation:

How to send a message to a thread that is doing a lengthy operation?

I have a main thread, and a worker thread. When the main thread is about to terminate, I need to send a message to the worker thread so it can terminate itself cleanly (I have heard that TerminateThread() is a bad idea).

The worker thread will be doing a lengthy operation (that will take more than 30 seconds), so is there a way to send it a message while doing this lengthy operation somehow. Or maybe the design of my program is wrong and a worker thread should not be doing such length operations?

Upvotes: 2

Views: 203

Answers (3)

Andrew Komiagin
Andrew Komiagin

Reputation: 6556

As a general principle, do not terminate threads.

Your background worker thread can periodically check if the program wants to exit. You should use std::atomic<bool> to do that. Here is an example on how to use it.

#include <iostream>
#include <thread>
#include <atomic>

volatile std::atomic<bool> g_bExit(false);

void thread1()
{
   while( !g_bExit )
   {
      // do stuff here
   }
}

int main()
{
      std::thread th1(thread1);

      g_bExit = true;

      th1.join() ; // wait for thread
}

Upvotes: 2

Ajay
Ajay

Reputation: 18411

Use PostThreadMessage function to post a message to another thread. Another thread must be having message pump (not necessarily a GUI-message-pump). Use GetMessage in target thread to retrieve the message. You need to craft a structure (better approach), and send the structure object. Your structure would contain actual message type (Start, Message, Stop etc - set of enum values for example).

Or you may use new threading techniques of C++14 or use unbounded_buffer of VC++ concurrency runtime. You need to explore and find appropriate solution for your problem.

I didn't post any example, since this domain is quite large. You better search on the web for examples, references etc.

EDIT: I believe I have misunderstood the problem initially. Here is my solution: Use event synchronization object. In worker thread, wait for event through WaitForSingeObject (or WaitForMultipleObjects). From source thread call SetEvent on same synchronization object. Yes, there are new alternatives in C++ std::thread

Upvotes: 0

aitorkun
aitorkun

Reputation: 39

An easy solution, but maybe not the best one is to use a global flag variable, initially with 0 value.

When the main thread finishes set it to one. Your other thread should check for this variable in a loop.

when the variable is 1 then the thread knows that the main thread has finished.

Hope it helps!

Upvotes: 0

Related Questions