How to deal with the second event loop with sending messages?
I am working on a program that is essentially single-threaded and its only thread is the main thread of the event loop. Hence, all of its data structures are mostly not protected by anything like a critical region.
Everything works fine until it integrates some new functionality based on the DirectShow API. Some DirectShow APIs open a second event loop and send messages during that second loop (ie, invoke event callbacks unpredictably). Therefore, when the second event-handling function is called, it can corrupt the data structure accessed by the function that calls the DirectShow API.
I have some kernel programming experience. And what comes to mind is that for a single threaded program, the way it should work with its data structure is very similar to how the kernel should deal with the data structure of each processor. And in the kernel, when a function accesses data in one cpu, it should disable the interrupt (much like sending messages in the second event loop). However, I believe there is no easy way to avoid calling the DirectShow APIs, or to prevent the creation of a second event loop inside them, is there a way?
a source to share
There are several possible solutions that come to mind, depending on what is going wrong and your code:
- Make sure your data structures are in a consistent state before calling any APIs that trigger the modal loop.
- If this is not possible, you can use a simple boolean variable to protect the structure. If it is installed, then simply abort any attempt to update it, or leave the update in the queue for later. Another option is to abort the previous operation.
- If the issue is related to custom events, disable the problematic menus or buttons during the operation. Alternatively, you can display a modal dialog.
a source to share