For example, do I need to lock a bool
value when multithreading?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
There is no such thing as an atomic type. Only operations can be atomic.
Reading and writing a data type that fits into a single word (
int
on a 32-bit processor,long
on a 64-bit processor) is technically "atomic", but the jitter and/or processor can decide to reorder instructions and thus create unexpected race conditions, so you either need to serialize access withlock
, use theInterlocked
class for writes (and in some cases reads), or declare the variablevolatile
.The short answer is: If two different threads may access the same field/variable and at least one of them will be writing, you need to use some sort of locking. For primitive types that's generally the
Interlocked
class.Similar Question here
Essentially, you wont have a "crash" problem from not locking a bool. What you may have is a race condition for the order of which the bool is updated or read. If you want to garuntee that the bool is written to/read from in a specific order, then you'd want to use some sort of locking mechanism.
Sort of. There's an excellent thread about this here, but the short version is, while a given read or write may be atomic, that's almost never what you're doing. For example, if you want to increment an integer, you need to 1) read the value, 2) add one to the value and 3) store the value back. Any of those operations can be interrupted.
That's the reason for classes such as "Interlocked".
Static primitive types are threadsafe, so you don't need to lock those typed variables. However, any instance variable of a primitive type is not guaranteed to be. See here: Are primitive types like bool threadsafe ?
MSDN PrimitiveType Class
And here's another useful link that might also be of interest which I find the solution very compelling: SO Question: How do I know if a C# method is thread safe?