Senthil
Senthil

Reputation: 21

Considerations when using lock

I have one small confusion. i am using one static variable called status with property in c# as follows

private static bool status;

public static bool Status   
{  
   get { return status; }  
   set { status = value; }  
}

Now i have started 2 threads separately First thread sets the value using property for variable status as true/false Second thread gets the value using property for variable status.

Here in this scenario, i thought like what would happen
if first thread tries to update the value of variable status while second thread tries to read the value of variable status

Whether i need to use lock statement for this variable status inside property to handle thread synchronization or its not needed? Could anyone help me by clarifying this doubt?

Upvotes: 0

Views: 137

Answers (2)

ferosekhanj
ferosekhanj

Reputation: 1074

From your question I understand thread one produces the status value and thread two consumes that value and does some work based on that. Here there is no lock required since reading from the primitive type is thread safe (while you are reading the data other thread wont corrupt that). lock is required only when you have two or more writer threads that want to write data. For eg if both your thread is going to set the Status value then a lock block is required.

Upvotes: 1

Antoine Aubry
Antoine Aubry

Reputation: 12469

Synchronizing access inside the property won't achieve anything, because a lock is meant to prevent access to a shared resource across a block of code that makes use of that resource.

What needs to be synchronized is the entire block that accesses the property. In general, you need to synchronize access at the caller level.

void Thread1() {
    lock(myObj) {

        if(myObj.Status)
            Console.WriteLine("Status is true");

        // ...

        // myObj.Status is guaranteed to be still true as long as
        // all the code that accesses the property lock myObj.
        if(myObj.Status)
            Console.WriteLine("Status is still true");

    }
}

Note that you do not need to lock the object that has the property. You can use another object as a synchronization mechanism, as long as it is shared between all the related threads.

static object mutex = new object();

void Thread1() {
    lock(mutex) {

        if(myObj.Status)
            Console.WriteLine("Status is true");

        // ...

        // myObj.Status is guaranteed to be still true as long as
        // all the code that accesses the property lock myObj.
        if(myObj.Status)
            Console.WriteLine("Status is still true");

    }
}

Upvotes: 0

Related Questions