2

I am working on an application with multiple threads (using Qt, C++). One of this threads is designed to execute a batch of operations like reading/writing from/to files as well as creating new ones. Sometimes, while this worker thread is active, I need some sort of confirmation from the user for operations like overwriting a file; I was thinking about doing this by emitting a signal from the worker and waiting for a response from the UI thread, which will show a popup and then give back the result; but I think this is an anti-pattern for asynchronous programming.

Are there any good, safe patterns to manage a problem like this?

2 Answers 2

1

Any sort of cross thread communication may become problematic. Try storing the user input in a common place and have the worker thread pole for a value in the common place periodically and act based on that.

1

Obviously, when you're doing this, you are essentially forcing the threads to synchronize, thus - as you say - defying the whole point of having separate threads. Yet, if those confirmations are rare, that may still be quite acceptable, and Qt::BlockingQueuedConnection is one really convenient way to handle inter-thread communication in that case.

Presumably, though, your main worry is keeping the UI alive, while actually, the user is expected to wait for the worker thread to do its thing. Depending on the details of what your worker thread is actually doing, you may want to look into QCoreApplication::processsEvents() as an alternative approach. This would allow you avoid threading, altogether. (This approach assumes that you will have an opportunity to call processEvents() regularly, during the task, of course.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.