Thread Safety is a concept that is much too heard and least implemented by developers. Locking basically enforces access rules and that also exclusive access. Locking ensures that only one thread can enter particular sections of code at a time.
class clsTestUnsafeClass
{
static bool bln = true;
static void Job()
{
if (bln)
{
Console.WriteLine ("bln will be false now");
bln = false;
}
}
}
The above code is not thread safe because if Job is called by two threads simultaneously it would be possible that both threads write "bln will be false now".
This is because it could be that one thread has validated the condition bln = true and has written on the console and before it sets bln=false, the time slice for this thread finishes and a new thread enters the if(bln) loop. Since previous thread has not yet set bln=false, the new thread can easily enter the condition and will also write "bln will be false now". Thus both the threads have written the same line although it was not intended.
Inorder to avoid this, we use locking mechanism:
class clsTestThreadsafeClass
{
static bool bln = true;
staic object dummyobject = new object();
static void Job()
{
lock(dummyobject)
{
if (bln)
{
Console.WriteLine ("bln will be false now");
bln = false;
}
}
}
}
The above code will lock the fragment of code after the lock statement for one thread. This means that if one thread has entered a lock block and its time slice has finished, even if a new thread reaches the lock block, it will be denied entry into the lock block till it is freed by the old thread which has entered first into the lock block. Thus the second thread will be blocked outside the code block till the first thread completes execution in the block and thus there will be no uintentional code effects due to time slicing.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment