I came up with an interesting situation. I have a bool variable and then I want multiple threads to perform its own independent tasks and then mark that bool depending on the thread's result. This variable is never read by any of the threads and is never used before all writing tests have finished. Like this:
public bool F(){
bool flag = false;
Parallel.ForEach(list, element =>
{
bool result = // Do independent work here;
if (result) flag = true;
});
return flag;
}
Notice how I never read flag inside my Parallel.ForEach. But what could happen is having multiple threads attempting to write true to flag (but never false). Is it safe to do this?
Yes, this is absolutely safe to do. The only thing that could happen is multiple threads writing true
into flag
concurrently, so you don't know which thread would end up overriding what result, but the end result is going to be the same.
By the time you read the flag all the writing has finished, and you never attempt to write anything except true
into flag
. Hence, the only two situations that you could see are as follows:
flag
- in this case the flag
would remain false
, ortrue
into the flag
- in this case the flag would be set to true
.If you want to avoid this situation altogether, and perhaps save some execution time, you could do this:
return list.AsParallel().Any(element => {
bool result = // Do independent work here
...
return result;
});
This code will not result in equivalent execution path, because the execution may stop early if one of the threads returns true
. If this is not desirable, keeping your ForEach
approach is fine, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With