Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Multithreading - Do I need to synchronise access to a variable of primitive type?

The scenario

I have a class with a bool Enabled property, that is used by a loop on another thread to see whether it should stop or not. The idea is that a different thread can set that property to false and stop the other thread running cleanly.

The question

Should I bother to serialise access to that Enabled property using something like lock (lockObject) { ... }, or is it safe without?

like image 409
Neil Barnwell Avatar asked Aug 11 '09 10:08

Neil Barnwell


People also ask

Why do we need synchronization primitives?

Note that signals are saved, unlike condition variables. Useful for counting resources (initial value > 1), to implement mutexes (initial value 1) or to signal completion of code across threads (initial value 0). Some semaphore implementations allow decrementing by more than one.

Can two threads access same variable?

Only one thread can read and write a shared variable at a time. When one thread is accessing a shared variable, other threads should wait until the first thread is done. This guarantees that the access to a shared variable is Atomic, and multiple threads do not interfere.

Which of the following is not a synchronization primitive?

Critical section is not a synchronization primitive.

What synchronization primitive does the C# lock keyword make use of?

The lock keyword is a C# shortcut for using the System. Threading. Monitor class, which is a heavyweight primitive. The members of the Monitor class are static, which is why you must provide a lock object—this tells the Monitor class which critical region a Task is trying to enter.


2 Answers

Primitive type reads are atomic provided that they fit within a CPU read. Thus a 32 bit primitive type read is atomic on a 32 bit CPU, whereas a 64 bit type read is not. However, unless it is also volatile your other thread may not see changes due to caching.

like image 80
Brian Rasmussen Avatar answered Oct 16 '22 03:10

Brian Rasmussen


I think you only need to mark the boolean variable as volatile. This will ensure that the thread that you wish to stop running always sees the most updated value of this boolean.

like image 31
bruno conde Avatar answered Oct 16 '22 05:10

bruno conde