Shutting down multithreaded NSDocument - c++

I have an NSDocument-based Cocoa app and I have a couple of secondary threads that I need to terminate gracefully (wait for them to run through the current loop) when the users closes the document window or when the application quits. I'm using canCloseDocumentWithDelegate to send a flag to the threads when the document is closing and then when they're done, one of them calls [NSDocument close]. This seems to work peachy keen when the user closes the document window, but when you quit the app, it goes all kinds of wrong (crashes before it calls anything). What is the correct procedure for something like this?

The best possible way is for the threads to own the objects necessary for the thread to finish doing whatever it is doing to the point of being able to abort processing and terminate as quickly as possible.
Under non-GC, this means a -retain that the thread -releases when done. For GC, it is just a hard reference to the object(s) desired.
If there is some kind of lengthy processing that must go on and must complete before the document is closed, then drop a sheet with a progress bar and leave the document modal until done (both Aperture and iPhoto do exactly this).

Related

Converting a Console Program into an MFC app (Thread issues) (Pleora SDK)

Back to stackoverflow with another question after hours of trying on my own haha.
Thank you all for reading this and helping in advance.
Please note the console program has following functionalities:
connect to a frame grabber
apply some configs
store the incoming data (640 * 480 16-bit grayscale imgs) in a stream of buffers inside a while loop
Exits the while loop upon a key press.
disconnect from device
And I'm only adding the displaying the images functionality on the MFC GUI app. In short,
i) Converting a console app to an MFC app (dialog based)
ii) decided to use thread for displaying images, but DK how to properly exit from thread when there are certain tasks to be done (such as call disconnectFromDevice(); freeBuffers();, etc) before exiting the thread.
iii) have tried making the while loop condition false but didn't work
( I actually want this to be a callback function that's called repeatedly but IDK how to implement it inside a thread)
iv) forcing AfxEndThread didn't work and it's not even the way it should be done (I think).
So my question is,
1. Are you supposed to use a while loop to excuete a certain job that should repeatedly be done? If not, do you have to implement a callback inside a thread? Or use Windows message loop? Why and how? Please provide a hello-world-like sample code example
(for example, you are printing "hello world" repeatedly inside a thread with a condtion in an MFC GUI app. How do you update or check the condition to end the thread if you can't just AfxEndThread() inside the threadproc)
2. If it's ok with a while, how do you exit from the while loop, in other words how do you properly update the exit condition outside the thread the while loop's in?
Please refer to the source code in the provided link
ctrl+F OnBnClickedConnectButton, AcquireImages and OnBnClickedDisconnectButton
https://github.com/MetaCortex728/img_processing/blob/main/IR140Dlg.cpp
Worker threads do not have message-queues, the (typically one and only) UI one does. The message-queue for a thread is created by the first call of the GetMessage() function. Why use messages to control processing in a worker thread? You would have to establish a special protocol for this, defining custom messages and posting them to the queue.
Worker threads can be implemented as a loop. The loop can be terminated based on various conditions, like failures to retrieve any data or request from the user. You can simply exit the thread proc to terminate the thread's execution. If the thread doesn't respond it may have stuck (unless it performs a really lengthy operation) and the UI thread must provide some mechanism to kill it. That is first request termination and if it doesn't respond within some set time then kill it.
The condition mechanism to terminate should best be some synchronization object (I would recommend a manual-reset event), interlocked variable or a simple boolean which you should access and set using a critical section.
Some considerations:
You pass a parameter block to the thread. Make sure that it remains alive throughout the thread's lifetime. For example, it should NOT be a local variable in a function that exits before the thread's termination.
The loop must be "efficient", ie do not loop infinitely if data are not available. Consider using blocking functions with timeouts, if available.
Resource management (eg connecting/disconnecting, allocating/releasing etc) should best be performed by the same thread.
An alternative implementation can be APCs. Then the thread's proc function is a while(!bTerminate) { SleepEx(INFINITE, TRUE); } loop, and other threads issue requests using a the QueueUserAPC() function.
The AfxEndThread(0) call in OnBnClickedDisconnectButton() is wrong, it terminates the current thread, which in this case is the main (UI) thread. Check the documentation.
A sidenote, my suggestion about the project type is not a dialog-based application but instead a normal MFC application without a document class (uncheck the Document/View architecture support option), as it offers features like menus, toolbars and the like, and most importantly the ON_UPDATE_COMMAND_UI handlers.

C++ Program freezing and UI turn all white

I'm working in a software built in C++ using C++ Builder which is freezing once a month.
I'm looking in the code but it is too big to find it.
The freezes make the UI gets all white. I tried to simulate this error with some proposital bad codes (null pointers, while(1) and this kind of stuff) but never got the same blank UI.
I ran a What's Hang when it's stopped but I got nothing with it.
Someone knows what can I do in the next time to get more informations which could help me find the reason of the freezing?
A blank (white) UI generally occurs when a UI paint message is queued but not processed. Simply blocking the message queue from processing new messages is not enough if you don't do something within the UI to trigger a repaint in the first place.
As for troubleshooting the original problem - you should be looking for any code in the main thread that runs longs loop without processing new messages, or long waits on waitable objects using WaitForSingleObject() or WaitForMultipleOBjects() instead of MsgWaitForMultipleObjects(), calls to TThread::WaitFor() for threads that do not terminate in a timely manner, etc.
It is hard to troubleshoot this kind of problem without knowing what steps the user performs to lead up to the frozen UI so you know what code to start looking at.

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.

Why can't my MFC app exit completely?

I made a MFC application which probably has two threads, one for receiving data from a socket using UDP protocol and one is the main thread of MFC app. While any data is received some objects, created in the main thread by new operator, would be notified to fetch the data through apply the observer design pattern. The problem is that sometimes after I clicked the close system button, the GUI of the app disappeared, but its process can still be found in the Task Manager. If I stop the data source (UDP client) this problem would never happen. Other important and maybe helpful information is listed below:
The Observer design pattern was implemented with STL container list. I have used the critical section protection in the Attach, Detach and Notify functions.
I deleted the observer objects before closing the UDP socket.
The data transfer rate may be a little faster than process data, because after closing the data source the data process is still working.
I can't figure out what lead my app can not exit completely. Please give me some clues.
This is usually caused by a thread you created and not exit it programmatically when you exit the appliation. There must be a while clause in your thread. The way to find where it is still running is:
use debug mode to start you application and click the exit button the top right corner to exit it.
Check from task manager and see if it is still running
if it is, excute Debug->Break All,
Open threads windows, double click each thread, you will find where your code is still looping.
Typically a process won't terminate because there's still a foreground thread running somewhere. You must ensure that your socket library isn't running any thread when you want to close your application.
First thing, with MFC, please use the notification based methods to get notifications on message arrivals, connections etc. So you can get rid of threads if you have.
It's quite easy to attache to a debugger and Break see which threads are existing and waiting for what.
Alternatively you can use ProcessExplorer with proper symbol configuration to see the call stacks of the threads available for the particular process.
The application can two kind of issues to exit, one could be infinite loop and other might be waiting/deadlock (e.g. socket read command is a blocking call). You can easily deduce the problem by attaching to debugger.
Otherwise please provide further information about the threads, code snippet possible.

C++ - Totally suspend windows application

I am developing a simple WinAPI application and started from writing my own assertion system.
I have a macro defined like ASSERT(X) which would make pretty the same thing as assert(X) does, but with more information, more options and etc.
At some moment (when that assertion system was already running and working) I realized there is a problem.
Suppose I wrote a code that does some action using a timer and (just a simple example) this action is done while handling WM_TIMER message. And now, the situation changes the way that this code starts throwing an assert. This assert message would be shown every TIMER_RESOLUTION milliseconds and would simply flood the screen.
Options for solving this situation could be:
1) Totally pause application running (probably also, suspend all threads) when the assertion messagebox is shown and continue running after it is closed
2) Make a static counter for the shown asserts and don't show asserts when one of them is already showing (but this doesn't pause application)
3) Group similiar asserts and show only one for each assert type (but this also doesn't pause application)
4) Modify the application code (for example, Get / Translate / Dispatch message loop) so that it suspends itself when there are any asserts. This is good, but not universal and looks like a hack.
To my mind, option number 1 is the best. But I don't know any way how this can be achieved. What I'm seeking for is a way to pause the runtime (something similiar to Pause button in the debugger). Does somebody know how to achieve this?
Also, if somebody knows an efficient way to handle this problem - I would appreciate your help. Thank you.
It is important to understand how Windows UI programs work, to answer this question.
At the core of the Windows UI programming model is of course "the message" queue". Messages arrive in message queues and are retrieved using message pumps. A message pump is not special. It's merely a loop that retrieves one message at a time, blocking the thread if none are available.
Now why are you getting all these dialogs? Dialog boxes, including MessageBox also have a message pump. As such, they will retrieve messages from the message queue (It doesn't matter much who is pumping messages, in the Windows model). This allows paints, mouse movement and keyboard input to work. It will also trigger additional timers and therefore dialog boxes.
So, the canonical Windows approach is to handle each message whenever it arrives. They are a fact of life and you deal with them.
In your situation, I would consider a slight variation. You really want to save the state of your stack at the point where the assert happened. That's a particularity of asserts that deserves to be respected. Therefore, spin off a thread for your dialog, and create it without a parent HWND. This gives the dialog an isolated message queue, independent of the original window. Since there's also a new thread for it, you can suspend the original thread, the one where WM_TIMER arrives.
Don't show a prompt - either log to a file/debug output, or just forcibly break the debugger (usually platform specific, eg. Microsoft's __debugbreak()). You have to do something more passive than show a dialog if there are threads involved which could fire lots of failures.
Create a worker thread for your debugging code. When an assert happens, send a message to the worker thread. The worker thread would call SuspendThread on each thread in the process (except itself) to stop it, and then display a message box.
To get the threads in a process - create a dll and monitor the DllMain for Thread Attach (and Detach) - each call will be done in the context of a thread being created (or destroyed) so you can get the current thread id and create a handle to use with SuspendThread.
Or, the toolhelp debug api will help you find out the threads to pause.
The reason I prefer this approach is, I don't like asserts that cause side effects. Too often Ive had asserts fire from asynchronous socket processing - or window message - processing code - then the assert Message box is created on that thread which either causes the state of the thread to be corrupted by a totally unexpected re-entrancy point - MessageBox also discards any messages sent to the thread, so it messes up any worker threads using thread message queues to queue jobs.
My own ASSERT implementation calls DebugBreak() or as alternative INT 3 (__asm int 3 in MS VC++). An ASSERT should break on the debugger.
Use the MessageBox function. This will block until the user clicks "ok". After this is done, you could choose to discard extra assertion failure messages or still display them as your choice.