This question already has answers here:
Avoiding "(Not Responding)" label in windows while processing lots of data in one lump
(11 answers)
Closed 7 years ago.
When an application fails to be responsive for 5 seconds (source), Windows can display "(Not Responding)" in the title bar and in some cases show a "not responding" dialog:
Ideally, the 5+ second execution should not block the main/event-processing thread, but is there a simple (e.g. 1 liner for MFC C++) way to communicate to Windows that the main thread is busy and shouldn't be treated as a "Not Responding" application to be closed? Is the quickest hack to simply periodically call peak PeekMessage with PM_NOREMOVE?
There really are no hacks to solve this. Any monkeying about with the message pump can lead to all manner of disaster, especially with COM and other system message processing.
Don't hold up the main thread.
Move the longer running tasks to a background or worker thread and either poll a future for completion or have the thread post a message back to the GUI to signal it is complete and then retrieve the result required.
In Windows 3.1 world all those eons ago, the answer was to divide your work into short-duration chunks, run the chunks in your window's message procedure and go from chunk to chunk by calling PostMessage.
Nowadays you update the window to show that the work is in progress, spawn a thread and call some PostMessage equivalent at the end of the thread so that your window can update itself back and show the results.
No, there's no quick hack, because your app is indeed not responding if you use the main thread like that.
Related
I'm working on a small framework for cross platform applications (sure, for academic purposes) and it needs to handle non-UI and UI programs gracefully. I'm currently investigating if having an OS message/event loop per window is possible. At this point I don't really care if it's a good idea, just if it's at all possible.
Now, on Windows, although I'd call WinMain, a non-UI (uh, windowless) program can still work through a messageloop. In this case, the main thread handles all messages that have their HWND parameter set to nullptr (the messages not sent to a specific window), and each window lives in its own thread, with its own wndproc called in its own message loop.
I believe a similar setup should be possible in X11, using a xcb_connection_t per thread (and thus per window). Assuming this is correct, what would be a good way of handling the "main" non-UI thread? If it does nothing, the program will exit immediately, regardless of how many other threads are running their X event loops. I'd like to keep this part X free. I've read about pause, sigsuspend etc. But I'm not sure these are the best fit for this somewhat simple purpose.
I have 3 simple program and each is a simple window. I will start all 3 of the process and then click on program 1 or 2's button to show up the window of program 3.
Program 1 & 2: Only have 1 button. When clicked, shows the hidden process of program 3(which is also a window).
Program 3: Starts up as a hidden process, and it is waiting for program 1 and 2's message before popping up. Depending on the button press, the window caption should change to the caption of program 1 or 2.
I am not sure what function or do I use a thread to make this behavior? I believe I need to use some sort of thread to do this.. first make program 3 hidden and then waiting for the message of program 1 and 2.. any ideas?
EDIT: I am using C++ and I am told to use a semaphore.
I would suggest using a Windows Event. Specifically, a Manual Reset Event. Your program 3 does a Wait on the event. When Program 1 or Program 2 wants to wake the window up, it sets the event. When Program 3 goes back to hiding, it clears the event.
You could use SendMessage or PostMessage, but the event seems much easier and straightforward. It also has certain advantages:
Program 1 and Program 2 don't need to find the window handle of Program 3, or broadcast a message that could be intercepted by some other process.
You can add security attributes to the event to prevent rogue programs from accessing it.
You can use the technique from a console application, a Windows service, or any other process, regardless of whether it's operating a message loop.
It's easier (for me, anyway) to understand than using Windows messages.
This isn't an appropriate use for a semaphore. A semaphore is typically used to synchronize access to multiple shared resources. All you want here is for Program 3 to wait for a notification, and for Program 1 or Program 2 to be able to send that notification.
If you have to pass data from Program 1 to Program 3, then the Event won't help you do that. You'll have to come up with a communication method such as a memory mapped file, pipe, network socket ... or even a Windows message in that case. But for simple "Hey, wake up!" notification, I'd use an event.
Since you need to communicate a simple message across a process boundary, I'd recommend using something in the SendMessage family. You will first need to acquire a handle for the target window. This function is pretty low-level in the windowing API, and so you'll only be able to get at it directly from C/C++, but you didn't specify what language you were using, and I think there are wrappers around this routine for the CLR accessible through C# as well.
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.
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.
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).