MFC application hangs in thread signaled for termination - c++

I'm writing an app in MFC with a background worker thread (created via _beginthreadex) and UI thread. A button is clicked from the UI thread to begin and end the worker thread. It starts the background thread if the m_threadRunning flag is false, and stops the background thread if it is true. The way I go about stopping the thread is I set the m_threadRunning flag to false and call WaitForSingleObject to let the background thread finish what it is doing.
My app has four different states. I had the first three states working properly, and adding the fourth state is what caused my problem. For the fourth state I want to be able to sample the desktop and send average RGB values to the COM port for processing. When in any of the first three states, if I want to stop execution of sending data to the COM port, it will terminate normally and without problems. If I am in the fourth state and click "stop", the application will hang since I have no time out on my call to WaitForSingleObject.
I also have a custom CEdit box CColorEdit that shows the current RGB values. I update this from the background thread when I'm in either state 3 or 4 (since they both change the colors dynamically). I've narrowed down the problem to a call to when I'm setting the color in which I call either Invalidate or RedrawWindow.
I've come up with a few solutions, but I don't like any of them and would rather understand what is causing the problem since my goal in writing this in MFC is to learn and understand MFC. Here is what has resolved the problem:
I call Sleep() in my worker thread already at about 60 samples/second. Changing this to a lower value, like 30 samples/second, resolved the problem most of the time.
I poll m_threadRunning in my worker thread to check if the thread should be terminated. If I poll it after sampling the screen but before updating the edit control, this resolves the problem most of the time.
I do a timeout of 5 seconds when calling WaitForSingleObject and call TerminateThread to manually kill the thread when it fails to wait, this resolves the problem all of the time. This is my solution in place for now.
Here are the relevant code bits (I lock around any use of outBytes):
void CLightControlDlg::UpdateOutputLabel()
{
CSingleLock locker(&m_crit);
locker.Lock();
m_outLabel.SetColor(outBytes[1], outBytes[2], outBytes[3]); //the call to this freezes the program
CString str;
str.Format(L"R = %d; G = %d; B = %d;", outBytes[1], outBytes[2], outBytes[3]);
m_outLabel.SetWindowText(str);
}
This section of code is for terminating the worker thread
m_threadRunning = false;
locker.Unlock(); //release the lock...
//omitted re-enabling of some controls
//normally this is just WaitForSingleObject(m_threadHand, INFINITE);
if(WaitForSingleObject(m_threadHand, 5000) == WAIT_TIMEOUT)
{
MessageBox(L"There was an error cancelling the I/O operation to the COM port. Forcing a close.");
TerminateThread(m_threadHand, 0);
}
CloseHandle(m_threadHand);
CloseHandle(m_comPort);
m_threadHand = INVALID_HANDLE_VALUE;
m_comPort = INVALID_HANDLE_VALUE;
The code in my derived edit control that updates the text color:
void SetColor(byte r, byte g, byte b)
{
_r = r;
_g = g;
_b = b;
br.DeleteObject();
br.CreateSolidBrush(RGB(r,g,b));
Invalidate(); //RedrawWindow() freezes as well
}
And finally, the code for my thread procedure:
unsigned int __stdcall SendToComProc(void * param)
{
CLightControlDlg *dlg = (CLightControlDlg*)param;
while(1)
{
if(!dlg->IsThreadRunning())
break;
switch(dlg->GetCurrentState())
{
case TransitionColor: //state 3
dlg->DoTransition();
dlg->UpdateOutputLabel();
break;
case ScreenColor: //state 4
dlg->DoGetScreenAverages();
//if(!dlg->IsThreadRunning()) break; //second poll to IsThreadRunning()
dlg->UpdateOutputLabel();
break;
}
dlg->SendToCom();
Sleep(17); // Sleep for 1020 / 60 = 17 = ~60samples/sec
}
return 0;
}
Any help you can provide is greatly appreciated!

You get a deadlock when the worker thread attempts to access controls that were created in the main thread and the main thread is suspended in WaitForSingleObject. Updating controls from the worker thread can only proceed when the main thread accepts the associated message to the control.
Remove all accesses to the controls from the worker thread. Instead, PostMessage a custom message to a window in the main thread. An example is here:
http://vcfaq.mvps.org/mfc/12.htm
The same technique could be used to notify the main thread that the worker thread has completed, so you could avoid WaitForSingleObject.

Related

How to stop a long-running function prematurely?

I am working on a plotting algorithm. To do this I get the data from a DAQ board in my main GUI thread and then I send the data over to a worker thread to be processed, the worker thread emits a signal with the new QImage which I display as a plot in my GUI. The problem is the function, let's call it generateImage(), to calculate and generate the QImage takes a long time (~50-70 milliseconds, depending on data length) and in between this time another set of data might arrive which will require the worker thread to recalculate the plot from the beginning. I want the generateImage() to abandon the calculation and restart from the beginning if the new data arrives while it is still calculating. My approach is to set a member boolean variable, let's call it b_abort_, and check if it is set to true inside generateImage() and return if it's true, outside generateImage() it always remains true and I only set it to false before generateImage() is called.
All this happens in a worker thread, I subclass QObject and use moveToThread() to move it to a worker thread.
The function which starts calculation:
void WorkerThread::startCalc()
{
b_abort_ = false;
generateImage();
// if b_abort_ is set to true, generateImage() will return prematurely
if(b_abort_)
emit calcFinished();
else
b_abort_ = true;
}
Function which does all calculations and generates image:
void WorkerThread::generateImage()
{
/* Calculation of some parts */
for(int ii = 0; ii < Rawdata.length(); ++ii) // Starting main time consuming loop
{
if(b_abort_)
return;
/* Perform calculation for one data point from Rawdata */
}
// data calculation complete, now it's time to generate QImage
// before that I check if b_abort_ is set to true
if(b_abort_)
return;
for(int ii = 0; ii < CalculatedData.length(); ++ii) // plotting calculated data on QImage
{
if(b_abort_)
return;
/* plot one data point from CalculatedData vector */
}
// generation of QImage finished, time to send the signal
emit renderedPlot(image); // image is a QImage object
}
In my worker thread, I have a slot to receive data from the main GUI Thread, it is configured with Qt::QueuedConnection (the default) as the connection type:
void WorkerThread::receiveData(QVector<double> data)
{
if(!b_abort_) // check if calculation is still running
{
QEventLoop loop;
connect(this, &WorkerThread::calcFinished, &loop, &QEventLoop::quit);
b_abort_ = true; // set it to true and wait for calculation to stop
loop.exec();
// start new calculation
RawData = data;
startClac();
}
else
{
RawData = data;
startClac();
}
}
When I use this approach in my main GUI Thread, the generateImage() function blocks all event loops, and my GUI freezes, which makes me think that inside a single thread (main GUI thread or a worker thread) only one function can run at a time and so any change in b_abort_ is not applied until the thread's event loop returns to process other functions. When using WorkerThread it is difficult to verify if this is working, some times it works fine while other times it generates bad allocation error which seems like it is not working (although it might be because of a different reason entirely, I am not sure). I would like to ask your opinion, is this the right approach to stop a long-running calculation prematurely? Are there any other methods that I can use which will be more robust than my current approach?
How to stop a long-running function in another thread prematurely?
You're correct that the only sane way to do this is to have the long-running thread check, at regular intervals, whether it should stop early.
Note that the flag you're checking must be atomic, or protected by a mutex, or otherwise somehow synchronized. Otherwise it's entirely legitimate for the worker thread to check the variable and never see the value change (no, you can't use volatile for this).
... which makes me think that inside a single thread (main GUI thread or a worker thread) only one function can run at a time ...
Yes, that's exactly what a thread is! It is a single, linear thread of execution. It can't do two things at once. Doing two things at once is the whole reason for having more than one thread.
The approach should be to have a worker thread waiting for work to do, and a main thread that only ever sends it asynchronous messages (start generating an image with this data, or interrupt processing and start again with this data instead, or whatever).
If the main thread calls a function that should happen in the worker thread instead, well, you've deliberately started executing it in the main thread, and the main thread won't do anything until it returns. Just like every other function.
As an aside, your design has a problem: it's possible to never finish generating a single image if it keeps being interrupted by new data.
The usual solution is double-buffering: you let the worker thread finish generating the current image while the main thread accumulates data for the next one. When the worker has finished one image, it can be passed back to the main thread for display. Then the worker can start processing the next, so it takes the buffer of "dirty" updates that the main thread has prepared for it. Subsequent updates are again added to the (now empty) buffer for the next image.

How to keep my camera alive when I use Cannon EDSDK in my C++ code?

I think it is essential to send a message to the camera per some minutes ,so I initialize my camera and send message to camera every once in a while in my main thread , and in the other thread I open the liveview to process my other jobs, but in the liveview thread , it wait time out when sending this message :
EdsSetPropertyData(theCamera, kEdsPropID_Evf_Mode, 0, sizeof(evfMode), &evfMode)
I never met this when all jobs handled in just one thread, I don't know why it happends like this , could someone help me ? Here is some of my code.
my main thread : (I don't send keepalive message in the thread,but also timeout when starting liveview !)
CanonCameraWrapper& wrapper = param->wrapper;
bool setup_ok = wrapper.setup(0);
if (!setup_ok)
{
wrapper.destroy();
}
wrapper.setDownloadPath("img");
pthread_t camera_thread;
pthread_create(&camera_thread, NULL, camera_thread_func, (void *)(param));
pthread_join(camera_thread, NULL);
the other thread
void * camera_thread_func(void * arg)
{
global_param* param = (global_param*)arg;
CanonCameraWrapper& wrapper = param->wrapper;
wrapper.beginLiveView();//**//it wait time out here!!!**
...
}
I believe there are two things you have to be aware of. One is this notice in the Canon SDK documentation:
When creating applications that run under Windows, a COM initialization is required for each thread in order to
access a camera from a thread other than the main thread.
To create a user thread and access the camera from that thread, be sure to execute CoInitializeEx( NULL,
COINIT_APARTMENTTHREADED ) at the start of the thread and CoUnInitialize() at the end.
Sample code is shown below. This is the same when controlling EdsVolumeRef or EdsDirectoryItemRef objects
from another thread, not just with EdsCameraRef
The other thing is: you cannot access (most of) the SDK at the same time. So if you are using multiple threads you have to be careful about this

Cancelling thread that is stuck on epoll_wait

I'm doing some event handling with C++ and pthreads. I have a main thread that reads from event queue I defined, and a worker thread that fills the event queue. The queue is of course thread safe.
The worker thread have a list of file descriptors and create an epoll system call to get events on those file descriptors. It uses epoll_wait to wait for events on the fd's.
Now the problem. Assuming I want to terminate my application cleanly, how can I cancel the worker thread properly? epoll_wait is not one of the cancellation points of pthread(7) so it cannot react properly on pthread_cancel.
The worker thread main() looks like this
while(m_WorkerRunning) {
epoll_wait(m_EpollDescriptor, events, MAXEVENTS, -1);
//handle events and insert to queue
}
The m_WorkerRunning is set to true when the thread starts and it looks like I can interrupt the thread by settings m_WorkerRunning to false from the main thread. The problem is that epoll_wait theoretically can wait forever.
Other solution I though about is: instead of waiting forever (-1) I can wait for example X time slots, then handle properly no-events case and if m_WorkerRunning == false then exit the loop and terminate the worker thread cleanly. The main thread then sets m_WorkerRunning to false, and sleeps X. However I'm not sure about the performance of such epoll_wait and also not sure what would be the correct X? 500ms? 1s? 10s?
I'd like to hear some experienced advises!
More relevant information: the fd's I'm waiting events on, are devices in /dev/input so technically I'm doing some sort of input subsystem. The targeted OS is Linux (latest kernel) on ARM architecture.
Thanks!
alk's answer above is almost correct. The difference, however, is very dangerous.
If you are going to send a signal in order to wake up epoll_wait, never use epoll_wait. You must use epoll_pwait, or you might run into a race with your epoll never waking up.
Signals arrive asynchronously. If your SIGUSR1 arrives after you've checked your shutdown procedure, but before your loop returns to the epoll_wait, then the signal will not interrupt the wait (as there is none), but neither will the program exit.
This might be very likely or extremely unlikely, depending on how long the loop takes in relation to how much time is spent in the wait, but it is a bug one way or the other.
Another problem with alk's answer is that it does not check why the wait was interrupted. It might be any number of reasons, some unrelated to your exit.
For more information, see the man page for pselect. epoll_pwait works in a similar way.
Also, never send signals to threads using kill. Use pthread_kill instead. kill's behavior when sending signals is, at best, undefined. There is no guarantee that the correct thread will receive it, which might cause an unrelated system call to be interrupted, or nothing at all to happen.
You could send the thread a signal which would interupt the blocking call to epoll_wait(). If doing so modify your code like this:
while(m_WorkerRunning)
{
int result = epoll_wait(m_EpollDescriptor, events, MAXEVENTS, -1);
if (-1 == result)
{
if (EINTR == errno)
{
/* Handle shutdown request here. */
break;
}
else
{
/* Error handling goes here. */
}
}
/* Handle events and insert to queue. */
}
A way to add a signal handler:
#include <signal.h>
/* A generic signal handler doing nothing */
void signal_handler(int sig)
{
sig = sig; /* Cheat compiler to not give a warning about an unused variable. */
}
/* Wrapper to set a signal handler */
int signal_handler_set(int sig, void (*sa_handler)(int))
{
struct sigaction sa = {0};
sa.sa_handler = sa_handler;
return sigaction(sig, &sa, NULL);
}
To set this handler for the signal SIGUSR1 do:
if (-1 == signal_handler_set(SIGUSR1, signal_handler))
{
perror("signal_handler_set() failed");
}
To send a signal SIGUSR1 from another process:
if (-1 == kill(<target process' pid>, SIGUSR1))
{
perror("kill() failed");
}
To have a process send a signal to itself:
if (-1 == raise(SIGUSR1))
{
perror("raise() failed");
}

C++: Thread synchronization scenario on Linux Platform

I am implementing multithreaded C++ program for Linux platform where I need a functionality similar to WaitForMultipleObjects().
While searching for the solution I observed that there are articles that describe how to achieve WaitForMultipleObjects() functionality in Linux with examples but those examples does not satisfy the scenario that I have to support.
The scenario in my case is pretty simple. I have a daemon process in which the main thread exposes a method/callback to the outside world for example to a DLL. The code of the DLL is not under my control. The same main thread creates a new thread "Thread 1". Thread 1 has to execute kind of an infinite loop in which it would wait for a shutdown event (daemon shutdown) OR it would wait on the data available event being signaled through the exposed method/callback mentioned above.
In short the thread would be waiting on shutdown event and data available event where if shutdown event is signaled the wait would satisfy and the loop would be broken or if data available event is signaled then also wait would satisfy and thread would do business processing.
In windows, it seems very straight forward. Below is the MS Windows based pseudo code for my scenario.
//**Main thread**
//Load the DLL
LoadLibrary("some DLL")
//Create a new thread
hThread1 = __beginthreadex(..., &ThreadProc, ...)
//callback in main thread (mentioned in above description) which would be called by the DLL
void Callbackfunc(data)
{
qdata.push(data);
SetEvent(s_hDataAvailableEvent);
}
void OnShutdown()
{
SetEvent(g_hShutdownEvent);
WaitforSingleObject(hThread1,..., INFINITE);
//Cleanup here
}
//**Thread 1**
unsigned int WINAPI ThreadProc(void *pObject)
{
while (true)
{
HANDLE hEvents[2];
hEvents[0] = g_hShutdownEvent;
hEvents[1] = s_hDataAvailableEvent;
//3rd parameter is set to FALSE that means the wait should satisfy if state of any one of the objects is signaled.
dwEvent = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);
switch (dwEvent)
{
case WAIT_OBJECT_0 + 0:
// Shutdown event is set, break the loop
return 0;
case WAIT_OBJECT_0 + 1:
//do business processing here
break;
default:
// error handling
}
}
}
I want to implement the same for Linux. According to my understanding when it would come to Linux, it has totally different mechanism where we need to register for signals. If the termination signal arrives, the process would come to know that it is about to shutdown but before that it is necessary for the process to wait for the running thread to gracefully shutdown.
The correct way to do this in Linux would be using condition variables. While this is not the same as WaitForMultipleObjects in Windows, you will get the same functionality.
Use two bools to determine whether there is data available or a shutdown must occur.
Then have the shutdown function and the data function both set the bools accordingly, and signal the condition variable.
#include <pthread.h>
pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_t hThread1; // this isn't a good name for it in linux, you'd be
// better with something line "tid1" but for
// comparison's sake, I've kept this
bool shutdown_signalled;
bool data_available;
void OnShutdown()
{
//...shutdown behavior...
pthread_mutex_lock(&mutex);
shutdown_signalled = true;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cv);
}
void Callbackfunc(...)
{
// ... whatever needs to be done ...
pthread_mutex_lock(&mutex);
data_available = true;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cv);
}
void *ThreadProc(void *args)
{
while(true){
pthread_mutex_lock(&mutex);
while (!(shutdown_signalled || data_available)){
// wait as long as there is no data available and a shutdown
// has not beeen signalled
pthread_cond_wait(&cv, &mutex);
}
if (data_available){
//process data
data_available = false;
}
if (shutdown_signalled){
//do the shutdown
pthread_mutex_unlock(&mutex);
return NULL;
}
pthread_mutex_unlock(&mutex); //you might be able to put the unlock
// before the ifs, idk the particulars of your code
}
}
int main(void)
{
shutdown_signalled = false;
data_available = false;
pthread_create(&hThread1, &ThreadProc, ...);
pthread_join(hThread1, NULL);
//...
}
I know windows has condition variables as well, so this shouldn't look too alien. I don't know what rules windows has about them, but on a POSIX platform the wait needs to be inside of a while loop because "spurious wakeups" can occur.
If you wish to write unix or linux specific code, you have differenr APIs available:
pthread: provides threads, mutex, condition variables
IPC (inter process comunication) mechanisms : mutex, semaphore, shared memory
signals
For threads, the first library is mandatory (there are lower level syscalls on linux, but it's more tedious). For events, the three may be used.
The system shutdown event generate termination (SIG_TERM) and kill (SIG_KILL) signals broadcasted to all the relevant processes. Hence an individual daemon shutdown can also be initiated this way. The goal of the game is to catch the signals, and initiate process shutdown. The important points are:
the signal mechanism is made in such a way that it is not necessary to wait for them
Simply install a so called handler using sigaction, and the system will do the rest.
the signal is set to the process, and any thread may intercept it (the handler may execute in any context)
You need therefore to install a signal handler (see sigaction(2)), and somehow pass the information to the other threads that the application must terminate.
The most convenient way is probably to have a global mutex protected flag which all your threads will consult regularily. The signal handler will set that flag to indicate shutdown. For the worker thread, it means
telling the remote host that the server is closing down,
close its socket on read
process all the remaining received commands/data and send answers
close the socket
exit
For the main thread, this will mean initiating a join on the worker thread, then exit.
This model should not interfer with the way data is normally processed: a blocking call to select or poll will return the error EINTR if a signal was caught, and for a non blocking call, the thread is regularily checking the flag, so it does work too.

EnterCriticalSection Deadlock

Having what appears to be a dead-lock situation with a multi-threaded logging application.
Little background:
My main application has 4-6 threads running. The main thread responsible for monitoring health of various things I'm doing, updating GUIs, etc... Then I have a transmit thread and a receive thread. The transmit and receive threads talk to physical hardware. I sometimes need to debug the data that the transmit and receive threads are seeing; i.e. print to a console without interrupting them due to their time critical nature of the data. The data, by the way, is on a USB bus.
Due to the threading nature of the application, I want to create a debug console that I can send messages to from my other threads. The debug consule runs as a low priority thread and implements a ring buffer such that when you print to the debug console, the message is quickly stored to a ring buffer and sets and event. The debug console's thread sits WaitingOnSingleObject events from the in bound messages that come in. When an event is detected, console thread updates a GUI display with the message. Simple eh? The printing calls and the console thread use a critical section to control access.
NOTE: I can adjust the ring buffer size if I see that I am dropping messages (at least that's the idea).
In a test application, the console works very well if I call its Print method slowly via mouse clicks. I have a button that I can press to send messages to the console and it works. However, if I put any sort of load (many calls to Print method), everything dead-locks. When I trace the dead-lock, my IDE's debugger traces to EnterCriticalSection and sits there.
NOTE: If I remove the Lock/UnLock calls and just use Enter/LeaveCriticalSection (see the code) I sometimes work but still find myself in a dead-lock situation. To rule out deadlocks to stack push/pops, I call Enter/LeaveCriticalSection directly now but this did not solve my issue.... What's going on here?
Here is one Print statement, that allows me to pass in a simple int to the display console.
void TGDB::Print(int I)
{
//Lock();
EnterCriticalSection(&CS);
if( !SuppressOutput )
{
//swprintf( MsgRec->Msg, L"%d", I);
sprintf( MsgRec->Msg, "%d", I);
MBuffer->PutMsg(MsgRec, 1);
}
SetEvent( m_hEvent );
LeaveCriticalSection(&CS);
//UnLock();
}
// My Lock/UnLock methods
void TGDB::Lock(void)
{
EnterCriticalSection(&CS);
}
bool TGDB::TryLock(void)
{
return( TryEnterCriticalSection(&CS) );
}
void TGDB::UnLock(void)
{
LeaveCriticalSection(&CS);
}
// This is how I implemented Console's thread routines
DWORD WINAPI TGDB::ConsoleThread(PVOID pA)
{
DWORD rVal;
TGDB *g = (TGDB *)pA;
return( g->ProcessMessages() );
}
DWORD TGDB::ProcessMessages()
{
DWORD rVal;
bool brVal;
int MsgCnt;
do
{
rVal = WaitForMultipleObjects(1, &m_hEvent, true, iWaitTime);
switch(rVal)
{
case WAIT_OBJECT_0:
EnterCriticalSection(&CS);
//Lock();
if( KeepRunning )
{
Info->Caption = "Rx";
Info->Refresh();
MsgCnt = MBuffer->GetMsgCount();
for(int i=0; i<MsgCnt; i++)
{
MBuffer->GetMsg( MsgRec, 1);
Log->Lines->Add(MsgRec->Msg);
}
}
brVal = KeepRunning;
ResetEvent( m_hEvent );
LeaveCriticalSection(&CS);
//UnLock();
break;
case WAIT_TIMEOUT:
EnterCriticalSection(&CS);
//Lock();
Info->Caption = "Idle";
Info->Refresh();
brVal = KeepRunning;
ResetEvent( m_hEvent );
LeaveCriticalSection(&CS);
//UnLock();
break;
case WAIT_FAILED:
EnterCriticalSection(&CS);
//Lock();
brVal = false;
Info->Caption = "ERROR";
Info->Refresh();
aLine.sprintf("Console error: [%d]", GetLastError() );
Log->Lines->Add(aLine);
aLine = "";
LeaveCriticalSection(&CS);
//UnLock();
break;
}
}while( brVal );
return( rVal );
}
MyTest1 and MyTest2 are just two test functions that I call in response to a button press. MyTest1 never causes a problem no matter how fast I click the button. MyTest2 dead locks nearly everytime.
// No Dead Lock
void TTest::MyTest1()
{
if(gdb)
{
// else where: gdb = new TGDB;
gdb->Print(++I);
}
}
// Causes a Dead Lock
void TTest::MyTest2()
{
if(gdb)
{
// else where: gdb = new TGDB;
gdb->Print(++I);
gdb->Print(++I);
gdb->Print(++I);
gdb->Print(++I);
gdb->Print(++I);
gdb->Print(++I);
gdb->Print(++I);
gdb->Print(++I);
}
}
UPDATE:
Found a bug in my ring buffer implementation. Under heavy load, when buffer wrapped, I didn't detect a full buffer properly so buffer was not returning. I'm pretty sure that issue is now resolved. Once I fixed the ring buffer issue, performance got much better. However, if I decrease the iWaitTime, my dead lock (or freeze up issue) returns.
So after further tests with a much heavier load it appears my deadlock is not gone. Under super heavy load I continue to deadlock or at least my app freezes up but no where near it use to since I fixed ring buffer problem. If I double the number of Print calls in MyTest2 I easily can lock up every time....
Also, my updated code is reflected above. I know make sure my Set & Reset event calls are inside critical section calls.
With those options closed up, I would ask questions about this "Info" object. Is it a window, which window is it parented to, and which thread was it created on?
If Info, or its parent window, was created on the other thread, then the following situation might occur:
The Console Thread is inside a critical section, processing a message.
The Main thread calls Print() and blocks on a critical section waiting for the Console Thread to release the lock.
The Console thread calls a function on Info (Caption), which results in the system sending a message (WM_SETTEXT) to the window. SendMessage blocks because the target thread is not in a message alertable state (isn't blocked on a call to GetMessage/WaitMessage/MsgWaitForMultipleObjects).
Now you have a deadlock.
This kind of #$(%^ can happen whenever you mix blocking routines with anything that interacts with windows. The only appropriate blocking function to use on a GUI thread is MSGWaitForMultipleObjects otherwise SendMessage calls to windows hosted on the thread can easily deadlock.
Avoiding this involves two possible approaches:
Never doing any GUI interaction in worker threads. Only use PostMessage to dispatch non blocking UI update commands to the UI thread, OR
Use kernel Event objects + MSGWaitForMultipleObjects (on the GUI thread) to ensure that even when you are blocking on a resource, you are still dispatching messages.
Without knowing where it is deadlocking this code is hard to figure out. Two comments tho:
Given that this is c++, you should be using an Auto object to perform the lock and unlock. Just in case it ever becomes non catastrophic for Log to throw an exception.
You are resetting the event in response to WAIT_TIMEOUT. This leaves a small window of opportunity for a 2nd Print() call to set the event while the worker thread has returned from WaitForMultiple, but before it has entered the critical section. Which will result in the event being reset when there is actually data pending.
But you do need to debug it and reveal where it "Deadlocks". If one thread IS stuck on EnterCriticalSection, then we can find out why. If neither thread is, then the incomplete printing is just the result of an event getting lost.
I would strongly recommend a lockfree implementation.
Not only will this avoid potential deadlock, but debug instrumentation is one place where you absolutely do not want to take a lock. The impact of formatting debug messages on timing of a multi-threaded application is bad enough... having locks synchronize your parallel code just because you instrumented it makes debugging futile.
What I suggest is an SList-based design (The Win32 API provides an SList implementation, but you can build a thread-safe template easily enough using InterlockedCompareExchange and InterlockedExchange). Each thread will have a pool of buffers. Each buffer will track the thread it came from, after processing the buffer, the log manager will post the buffer back to the source thread's SList for reuse. Threads wishing to write a message will post a buffer to the logger thread. This also prevents any thread from starving other threads of buffers. An event to wake the logger thread when a buffer is placed into the queue completes the design.