Monthly Archives: March 2006

Concurrent access to a small variable

When multithread-programming, you obviously need some synchronization mechanisms, such as semaphores, critical sections. This avoids that two threads access a resource at the same time, one for writing, the other one for reading.

Until now, I was cautiously protecting any variable concurrently accessed with those mechanisms.

And it took me a while to realize that it is not always necessary. As long as your variable is small enough to be read or set in one row from memory, you don’t need to protect it because a thread modifying this variable cannot be interrupted during the modification. The size of variables depends on your type of processor : must not exceed 32 bits on a 32 bits processo, 64 on a 64 bits processor.