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.
Should I bother to serialise access to that Enabled
property using something like lock (lockObject) { ... }
, or is it safe without?
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.
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.
Critical section is not a synchronization primitive.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With