Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to have multiple threads writing to the same bool if the value is never read?

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?

like image 413
Derek Patton Avatar asked Feb 11 '23 02:02

Derek Patton


1 Answers

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:

  • None of the threads write anything into flag - in this case the flag would remain false, or
  • One or more threads write true 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.

like image 52
Sergey Kalinichenko Avatar answered Feb 13 '23 20:02

Sergey Kalinichenko