|
Is it too much to ask for a decent example? In this case, the user is still doing just 1 task, with the addition of a cancel and progress button.
In reality, if calculation code reports progress and is cancellable, its probably easily performed synchronously, with a cancel-check at each progress update. When cancelled, the main thread would still have to join the threaded calculation's thread (or at least wait for it to cancel), so there is almost zero benefit to threading this example.
You've taken a trivial example that would work perfectly as a single-threaded task and popped it in a thread... I'd like to see an example that would be difficult to do in a single threaded world. Even the web responses isn't a great example, because theres always the ol' select() pattern that was once commonplace.
Can you post an example with some meat? Eg, doing two backgrounded tasks that work together would be a good start.
Even two independent backgrounded tasks can be difficult in a single-threaded context as it can be tricky to return control to the first task.
Eg faking backgrounding by calling QT's qApp->processEvents() regularly - this doesn't return control to the first task until the second task is done. For that to work, you have to break the computation into callable chunks and schedule the chunks with postEvent or a QTimer.
If that sort of thing was discussed, it might help educate those who don't fully understand why multithreading is so powerful.
Thanks
|
IF you tried your method then the User Interface would be totally stuck between progress bar updates. Plus there would be no way to cancel the operation! The thread would be stuck in your "for loop" and therefore the user interface/cancel button will not work! until you are out of the "calculation loop". Sure you can check if "cancel" has been hit between iterations, but guess what? your program will not have any time to actually notice mouse clicks.. its stuck in your "summing loop".
It's a simple task, but its not how simple the task is, its how much cpu time it takes up. If I tell you to count to 1 trillion, and i also tell you, "you cannot do anything else in life, until you are done counting to 1 trillion" then you will quickly die of starvation.. you cannot eat, sleep, walk, work, talk until you are done counting to 1 trillion... same for this app, if you use single thread, you cannot process mouse clicks until you are done summing up the numbers.
If you do not trust me, try it out... try this app, all within the UI thread. You'll notice quickly, you cannot cancel, you'll be starving the UI.