ive been asking myself : “why should i use lock to only one statement”…
(IMHO – if its 1 operation only like an assignment – so there shouldnt be a problem..)?
then i saw this :
As a basic rule, you need to lock around accessing any writable shared
field. Even in the simplest case—an assignment operation on a single
field—you must consider synchronization. In the following class,
neither the Increment nor the Assign method is thread-safe:
class ThreadUnsafe
{
static int _x;
static void Increment() { _x++; }
static void Assign() { _x = 123; }
}
can you please tell me why this is not thread safe ?
ive been running many scripts in my head and couldnt find any problem…
Here’s an example of why your example is not thread-safe. Initially,
_x = 0. Let’s say you runIncrementandAssignin parallel. If the methods were thread-safe, the result should be either100(if increment is executed before assign) or101(if increment is executed after assign).(EDIT: Note that each thread has it’s own working stack!)
_xis now1, which is neither100nor101.Of course, it could be that your incrementation method is compiled into single, atomic operation by the compiler. But you cannot rely on this, unless it is specifically guaranteed by the compiler that you use.
If you use a lock, the following happens:
The result is now
100. Basically, the lock ensures that two locked blocks do not overlap.