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.
Related
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.
I'm currently diagnosing an issue with window activation, where a call to SetForegroundWindow is failing, even though I believe it is being called from the foreground thread. The issue is reproducible when input comes from a touch digitizer.
Is there any way to find out, which thread received the last input? I tried calling GetWindowThreadProcessId on the handle returned from GetForegroundWindow. However, that appears to return outdated information, just after input activation of a window1).
Since this is only for diagnosing an issue, I'm happy with a solution using undocumented interfaces, if public interfaces aren't available. In case this matters, the target platform is Windows 7 64 bit.
1) GetForegroundWindow returns the same handle, irrespective of whether input comes from a touch digitizer or a pointing device. A subsequent call to SetForegroundWindow succeeds, when input comes from a pointing device, but fails for touch input.
Since this is only for diagnosing an issue, I'm happy with a solution using undocumented interfaces, if public interfaces aren't available.
You can try installing system wide hook for WH_GETMESSAGE with SetWindowsHookEx, and monitor interesting messages like WM_SETFOREGROUND. Ie. log interesting stuff before calling original version.
Another idea is to hook SetForegroundWindow API, with MHOOK or Detours. As you can see here https://superuser.com/questions/18383/preventing-applications-from-stealing-focus, using mhook looks preety simple.
GetWindowThreadProcessId does not return which thread last received input for a window. It tells you which tread created the window and therefore should be processing the input.
You have to know that Windows input works via messages. These messages are delivered to a thread message queue. This explains directly why each window has an associated thread: that's the thread to which the message is delivered.
In a normal application, all windows are created by a single "foreground" or "UI" thread. Therefore, the question "which thread recevied the last input" is always "the foreground thread". Background threads simply do not receive window messages.
Very few applications create multiple windows on multiple threads, even though this is allowed. In those cases, two threads can simultaneously receive messages, which makes the notion of "last input" invalid. Each thread has its own "last input" in these cases.
Getting back to your stated problem, SetForegroundWindow has no documented thread restrictions. In particular, there is no restriction that it has to be called from the foreground thread. In fact, the documentation states that it can be another process altogether (which certainly means another thread).
You specially mention "last input", but the restrictions only mention that in process context: "A process can set the foreground window only if ... the process received the last input event".
This does not answer the question that was asked, but addresses the root issue that led to this question:
The SetForegroundWindow API imposes several restrictions on which thread can successfully call it. One of the prerequisites is that the calling thread's
process received the last input event.
Unfortunately, on Windows 7 this does not include touch input. A process is not eligible to call SetForegroundWindow in response to WM_TOUCH. It is not until the system has synthesized a respective compatibility mouse input event, that the process finally gets foreground activation rights.
This has since changed, starting with Windows 8, where touch input counts as first-class input, and calling SetForegroundWindow succeeds in response to a WM_TOUCH message.
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.
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).