winapi threads take time to initialise before message passing works? - multithreading

I have a main program that creates the threads in order:
ThreadB then
ThreadA (which is passed ThreadB's ID)
using the CreateThread function.
Thread A sends a message to Thread B using PostThreadMessage.
B gets the message using GetMessage.
The problem I am having is that PostThreadMessage blocks randomly the first time it is called and never returns, some times the program funs fine, other times I run the program and it blocks with 0 CPU usage at the first postthreadmessage. However if I add Sleep(10) to ThreadA before the first PostThreadMessage, I never seem to encouter this problem.
What am I missing about the timing of threads and messages?

You cannot send a message to a thread until it has a message queue. Message queues are not created until that thread calls a function such as GetMessage or PeekMessage. What your sleep does is delay the sending thread long enough that the receiving thread has called GetMessage and set up its message queue.
Incidentally, I strongly recommend against using PostThreadMessage as the messages can get lost. It is better to create a message-only window (with a parent of HWND_MESSAGE) on the receiving thread and send messages to that instead.

To add to Anthony Williams correct answer, the code I use to deal with this looks like. I have a class similar to MyThread...
void MyThread::Start()
{
m_hResumeMain = CreateEvent(NULL,FALSE,FALSE,NULL);
m_hThread = CreateThread(NULL,0,ThreadProc,this,0,&m_dwThreadId);
WaitForSingleObject(m_hResumeMain,INFINITE);
CloseHandle(m_hResumeMain);
m_hResumeMain=0;
}
DWORD MyThread::ThreadProc(LPVOID pv)
{
MyThread* self = (MyThread*)pv;
return self->ThreadProc();
}
DWORD MyThread::ThreadProc()
{
MSG msg;
// Create the thread message queue
PeekMessage(&msg,0,0,0,PM_NOREMOVE);
// Resume the main thread
SetEvent(m_hResumeMain);
while(GetMessage(&msg,0,0,0)>0){
if(msg.hwnd){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else {
DoThreadMessage(&msg);
}
}
return 0;
}
The crux of the issue is you ultimately cannot rely on a Sleep to guarantee that the worker thread is sufficiently initialized. Plus, in general there is usually some mimimal amount of work a worker thread needs to have done before the launching thread should be allowed to resume. So create an event object before creating the thread, wait for it on the main thread and signal it on the worker thread once the initialization is done.

Related

How to ensure thread is not terminated before finalizer completes

I have an unmanaged class that is running a message loop for a child Win32 window. When the program goes to close, it starts the finalizer for the managed class that holds the unmanaged reference to this class. Because another thread is dependent on this class, I need the finalizer to wait until the message loop thread has completed a loop and exits and terminates. However, the timeout loop I have apparently takes too long for the GC finalizer thread or the main thread terminates destroying the entire process.
Is there a way to tell the GC to not timeout a thread for finalizers? I.E. - I need the finalizer thread to block for a little while in the finalizer so it can complete terminating the message loop thread and then release the unmanaged resource.
Here is my finalizer so you get an idea of what's going on:
PONms::NestedWin32::
!NestedWin32()
{
if (msgLoop->IsAlive)
{
winProcess->EndThread(); // blocks and waits for message loop thread to terminate
// and GC apparently doesn't like this causeing the
// entire process to terminate here.
}
if (childHandle != nullptr)
{
DestroyWindowCore(childHandle);
}
if (winProcess != nullptr)
{
delete winProcess; // memory leak due to resource not being released
}
}
I'm thinking I went about this the wrong way, just expecting the code to behave properly and the finalizer to complete.
Here is the simple method I use to poll the other thread to see if it has terminated:
void PONms::NestedWin32UM::
EndThread()
{
int timeOut = 5000;
threadContinue = false;
SendNotifyMessage(childWin, WM_CLOSE, 0, 0);
while (threadActive && timeOut > 0)
{
POCPP::Threading::SleepThreadOne();
timeOut--;
}
}
int timeOut = 5000;
That is a pretty drastic mismatch with the default CLR policy for the finalizer thread timeout. You've got 2 seconds to get the job done. Roughly 10 billion instructions on a modern processor. We can't see what SleepThreadOne() does, but Sleep(1) doesn't sleep for 1 millisecond. Default sleep granularity is 15.625 msec so you'll end up waiting for as long as 78 seconds.
Technically you can extend the timeout by custom-hosting the CLR, ICLRPolicyManager::SetTimeout() method, OPR_FinalizerRun setting. But, realistically, if you can't hack it with 10 billion instructions then extending it isn't very likely to bring relief.
Debugging this isn't that simple, those 2 seconds are over in a hurry. Look at structural fixes. Don't use a bool to synchronize code, use an event (CreateEvent winapi function). And WaitForSingleObject() with a timeout to wait for it to be set. Use 1000 msec max so you give the finalizer thread enough breathing room. And don't be too nice asking the message loop to quit, WM_CLOSE is far too friendly. Code is apt to respond to it with a "Save changes?" message box, that's a guaranteed fail. Use PostQuitMessage(). Or don't bother at all, programs should terminate through the UI and you seem to need to pull the rug another way.

Qt: How do I catch signals from multple threads in a slot where all signals are queued

I have a condition where I have unknown amount of 3rd party threads calling a callback in my application. That callback emits a signal in the context of the threads that called it. Always the same signal, but 10 different threads can emit it at any given moment.
I'd like to queue all of those singlas and process them with the appropriate slot in the context of a single QThread I own.
How do I do that? The following code does not work. Although I see it signals being emitted, from different threads, my "On..." is never called.
QObject::connect(this,SIGNAL(ProcessQueuedOutEvent(int)),
this,
SLOT(OnProcessQueuedOutEvent(int)),
Qt::QueuedConnection);
Does your QThread run the event loop? It has to do it to receive signals:
Queued Connection The slot is invoked when control returns to the
event loop of the receiver's thread. The slot is executed in the
receiver's thread.
Basically queued connection works the following way:
The originator issues a signal.
Qt creates an event and posts it into the receiver event queue.
The receiver goes through its event queue, picks up the events and dispatches the signals into the connected slots.
Hence if you do not run the event queue, the signals are posted but your thread will never receive them.
So basically your thread should do some initialization in run() but then call exec() and pass it to Qt.
If your thread also needs to run some periodic operations besides checking for signals, you can do that by using QTimer::singleShot timers posting signals to the same thread.
See http://qt-project.org/doc/qt-4.8/threads-qobject.html#signals-and-slots-across-threads
PS. If you pass the pointers via queued connections, the pointer must be valid until the signal is processed, which may be after your function which posted the signal existed. A common error is to post signals with strings as a parameters which are stored in a local char[] buffer. At the moment the buffer is accessed the original function is finished, and the string is already gone. Those errors depend on thread scheduling and therefore hard to debug. If you pass the pointers via queued connection, they must be heap-allocated and the callee must be responsible to free them.
If I understand your problem correctly, you have a callback function executed by many threads. This callback function should emit a signal connected to a slot in a object which is in another thread.
What I suggest is to create a threaded receiver object, using the pattern (moveToThread). Then using the postEvent method to a private implementation method. The call is thread safe (the parameter is copied).
So your callbacks can directly and safely call:
OnProcessQueuedOutEvent
which posts an event to the QThread event loop.
Receiver.h
class Receiver : public QObject
{
Q_OBJECT
public:
explicit Receiver( QObject* parent = 0 );
virtual ~Receiver();
public slots:
void OnProcessQueuedOutEvent( int val );
private slots:
void OnProcessQueuedOutEventImpl( int val );
private:
QThread m_thread;
};
Receiver.cpp
Receiver::Receiver( QObject* parent )
: QObject(parent)
{
moveToThread(&m_thread);
m_thread.start();
}
Receiver::~Receiver()
{
// Gracefull thread termination (queued in exec loop)
if( m_thread.isRunning() ) {
m_thread.quit();
m_thread.wait();
}
}
void OnProcessQueuedOutEvent( int val )
{
QMetaObject::invokeMethod(this, "OnProcessQueuedOutEventImpl", Q_ARG(int,val));
}
void OnProcessQueuedOutEventImpl( int val )
{
// do stuff here
}

Akka : message processing against thread utilization

When message comes in mailbox, scheduler picks an actor, resume it and put it on OS thread. Java threads maps with OS thread to do execution.
Actor will use one thread from pool and use this thread for messages processing and release the thread to pool.
Actor doesn't have dedicated thread. There is a pool of threads and an actor will use allotted thread for processing message and once message processing done, thread will be released. So, Actor is decoupled from thread.
Now lets take an example :
public class GreetingActor extends UntypedActor {
LoggingAdapter log = Logging.getLogger(getContext().system(), this);
public void onReceive(Object message) throws Exception {
if (message instanceof String) {
String sRmsg = (String) message;
businessImpl.collectdata(sRmsg); // assume this method takes 1 mins for completion
}
}
}
ActorSystem system = ActorSystem.create("MySystem");
ActorRef greeter = system.actorOf(new Props(GreetingActor.class), "greeter");
greeter.tell("Charlie Parker");
Here, greeter actor sends message using tell method, So this message will go in mailbox queue and scheduler will pick the message from queue and invoke actor with the message.
When the message is received in GreetingActor's 'onReceive' method - My question is when will the actor-utilized Thread be released back to the pool-
Either after receiving message in onReceive method OR after execution of collectdata() method ?
Also, What does 'Message Processing' indicate ?
businessImpl.collectdata(sRmsg); // assume this method takes 1 mins for completion
If this line can potentially take that much time, then it should be
considered as a blocking call. There is a section in the documentation
that explains how such situations can be handled safely:
http://doc.akka.io/docs/akka/2.1.0/general/actor-systems.html#blocking-needs-careful-management
When the message is received in GreetingActor's 'onReceive' method - My
question is when will the actor-utilized Thread be released back to the
pool-
Either after receiving message in onReceive method OR after execution of
collectdata() method ?
It will "release" the thread back to the pool after the execution of
the long collectdata() call -- therefore the above code is dangerous.
The link I pasted above has some nice patterns how to work around
this, IF you can not split up the task into smaller pieces (for
example because you use an external library you have no control over).
If you can split up that method into finer granularity short-time
tasks handled by actors and message passing, then you don't need the
special handling.
-Endre,
Akka Team

Thread scheduling issue with MFC and AfxBeginThread

I'm creating a worker thread in MFC with AfxBeginThread, but the thread is not getting scheduled. Here's the code:
CWinThread* worker = AfxBeginThread(initialUpdateWorkerThread, this);
DWORD dwExitCode = 0;
while(GetExitCodeThread(worker->m_hThread, &dwExitCode))
{
if(dwExitCode != STILL_ACTIVE)
break;
::Sleep(100);
}
When I run this, this loop just livelocks because initialUpdateWorkerThread is never called (I've put break points and message boxes at the top of it) so dwExitCode is always STILL_ACITVE. But if I put in a call to AfxMessageBox before the loop but after AfxBeginThread then the function is called. This makes me think that somehow I'm not calling the right function to get the thread scheduled, but a call to AfxMessageBox causes it to get scheduled.
How can I force the thread to be scheduled? I would think sleep would do that, but in this case it doesn't seem to.
Your worker thread is probably trying to send your main thread a message, but since you aren't processing messages on on the main thread, the worker thread simply waits. You can confirm this by simply breaking into the debugger to see what the worker thread is doing.

How to wait in the main thread until all worker threads have completed in Qt?

I have designed an application which is running 20 instance of a thread.
for(int i = 0;i<20;i++)
{
threadObj[i].start();
}
How can I wait in the main thread until those 20 threads finish?
You need to use QThread::wait().
bool QThread::wait ( unsigned long time = ULONG_MAX )
Blocks the thread until either of
these conditions is met:
The thread associated with this
QThread object has finished execution (i.e. when it returns from
run()). This function will return true if the thread has finished. It
also returns true if the thread has
not been started yet.
time milliseconds has elapsed. If time is
ULONG_MAX (the default), then the wait
till never timeout (the thread must
return from run()). This function
will return false if the wait timed
out.
This provides similar functionality to
the POSIX pthread_join() function.
Just loop over the threads and call wait() for each one.
for(int i = 0;i < 20;i++)
{
threadObj[i].wait();
}
If you want to let the main loop run while you're waiting. (E.g. to process events and avoid rendering the application unresponsible.) You can use the signals & slots of the threads. QThread's got a finished() singal which you can connect to a slot that remembers which threads have finished yet.
You can also use QWaitCondition
What Georg has said is correct. Also remember you can call signal slot from across threads. So you can have your threads emit a signal to you upon completion. SO you can keep track of no of threads that have completed their tasks/have exited. This could be useful if you don't want your Main thread to go in a blocking call wait.

Resources