How to operate components in two different threads


#1

I want to show a dialog that display a message text and a cancel button in a separate thread from the main thread. How can I achieve this ?
And more general: Is there a simple way to use Juce Components in more than one thread ?


#2

No, components aren’t designed to be used by multiple threads. Being an event-based model that wouldn’t really make a lot of sense. Better to send messages to your components from a background thread than to control them directly.

A thread can grab a MessageManagerLock if it needs to interact with a component, but you need to be very careful because you can easily get some very nasty deadlocks that way.


#3

My challenge is that the main thread is busy with some lengthy computation and I want to cancel it. Unfortunately it is nor trivial to move the computation into a worker thread. So having any option to run just a cancel button in a separate thread would be great. I also tried a single threaded solution where I invoke MessageManager::runDispatchLoopUntil from my cancel hook in the processing routine. This goes to sleep by itself thus slowing computation down by a huge amount. Ideally I could simply process the pain messages for all components and all messages for the cancel button cery quickly from the main thread. I something like this possible ?


#4

Have you looked at the ThreadWithProgressWindow?


#5

Yes, but it assumes that the UI is in running within the main thread and the processing is done in the worker tread. I would need something vice versa. I cannot move the processing to a worker thread without major effort.


#6

Well, your choices are to either do things properly, and run your work on a background thread, or do the hacky single-thread/runDispatchLoopUntil thing. There’s simply no other possibility - OSes won’t let you dispatch messages using another thread.


#7

Modal dialog boxes should be avoided anyway, don’t they not work on Android?