Tuesday, May 8. 2007

Multithreading is hard

The article Memory Barrier at ridiculous fish describes an interesting observation when doing multithreading.

Assume you have a writer thread that increments two global variables continously:

while (1) {
   variable1++;
   variable2++;
}

The reader thread reads the two global variables continously:

while (1) {
   local2 = variable2;
   local1 = variable1;
   if (local2 > local1) {
      print("Error!");
   }
}

The reader thread reads the variables in the reverse order to assure that local2 <= local1, as the writer thread increments local2 after local1. If you think that this condition always holds, read the blog entry on
Memory Barrier to see why it doesn't. As you may already have guessed, you need a memory barrier to ensure this condition.

(Thanks to copton for pointing me to the blog entry.)