There are many moments where our multi-threaded code needs to gurantee only one code path is executing at a time. That’s why we have locks, semaphores, mutexes, and so on. But those are all pretty complicated. Vincent H recently was reviewing someone’s code, and they found a far more elegant solution, which simply uses booleans.
For example, you could whip up a wait loop with a simple block like this:
while (Busy)
{
// wait for it..
}
When Busy
becomes false, thanks to another thread changing its value, this loop will exit. Of course, sharing values between threads introduces its own possible issues, so in context, we’ll write a method that looks more like this:
public static List<T> GetMyList<T>(this List<T> list, bool Busy, string FilePath, string FileName)
{
var myfilepath = FilePath + FileName;
while (Busy)
{
// wait for it..
}
…
}
By passing Busy
as a parameter (a by-value parameter, in this case), we guarantee that no other running threads will change the value of it while we’re waiting for it to change. This is a great solution to mutexes, because it guarantees that if you call this method while you’re Busy
doing something else, this just enters an infinite loop from which it never exits, guaranteeing that you never accidentally do something you shouldn’t do.