Just use a mutex from your threading library. There's little point in trying to invent your own locking mechanism (which won't work as shown above, since even boolean assignments are not guaranteed to be atomic) when there are perfectly good locks readily available.