The classical way to protect access to a variable is using a mutex.
NOTE: This is known to have much overhead.
Basic Example
Class Example