Hi, I have question about exiting the while loop. I'm writing code in which I'm creating two threads, which prints strings and main() part has to print dots(".") every 500 miliseconds. Can you please help me how to exit the while loop after the second thread terminates, to get something like this on output:
...Hello...World....THE END
Instead of 'sleep' you could try joining the threads with a timeout, and end the loop when the join succeeds (but continue if you reach the timeout, of course)
@L B: That is always going to be the case with any flag used across threads. The only alternative is to lock the entire section of code that relies on that flag, but that often negates the benefit of threading.
If you're using a flag it's fine to have it change after you check it as long as the other thread changing it does not modify anything that would cause issues (e.g closing a file). But this comes back to designing the responsibilities of your threads appropriately.
Using raw booleans and active waiting is wasting CPU cycles and asking for some other trouble and L B is right. The obvious alternative is using Hoare's monitor (signal / wait pair) or, if we allow threads to exit, just joining them as L B said.
The problem with only setting a boolean flag is the thread that sets it has no control over the state of the threads it wants to signal / break. It just continues. Which means it must not be allowed to reset this flag back ever.
BTW: The flag needs to be volatile, not only static. And static mutable data are code-smell.