views:

115

answers:

3

I'm not quite sure how to word this, so I'll just paste my code and ask the question:

private void remoteAction_JobStatusUpdated(JobStatus status) {
    lock (status) {
        status.LastUpdatedTime = DateTime.Now;
        doForEachClient(c => c.OnJobStatusUpdated(status));
        OnJobStatusUpdated(status);
    }
}

private void doForEachClient(Action<IRemoteClient> task) {
    lock (clients) {
        foreach (KeyValuePair<RemoteClientId, IRemoteClient> entry in clients) {
            IRemoteClient clientProxy = entry.Value;
            RemoteClientId clientId = entry.Key;
            ThreadPool.QueueUserWorkItem(delegate {
                try {
                    task(clientProxy);
#pragma warning disable 168
                } catch (CommunicationException ex) {
#pragma warning restore 168
                    RemoveClient(clientId);
                }
            });
        }
    }
}

Assume that any other code which modifies the status object will acquire a lock on it first.

Since the status object is passed all the way through to multiple ThreadPool threads, and the call to ThreadPool.QueueUserWorkItem will complete before the actual tasks complete, am I ensuring that the same status object gets sent to all clients?

Put another way, when does the lock (status) statement "expire" or cause its lock to be released?

A: 

i think , you should not lock on status as status is a parameter and it may change for multiple threads.

i don't think your thread synchronization is working correctly.

you should use a custome object like object objLock = new object();

and then use locking with this object only.

saurabh
+5  A: 

Locks don't expire. When a thread tries to pass the lock statement it can only do it if no other thread is executing inside a lock block having a lock on that particular object instance used in the lock statemement.

In your case it seems that you have a main thread executing. It will lock both the status and the clients instances before it spins of new tasks that are executed on seperate threads. If any code in the new threads want to acquire a lock on either status or clients it will have to wait until the main thread has released both locks by leaving both lock blocks. That happens when remoteAction_JobStatusUpdated returns.

You pass the status object to each worker thread and they are all free to do whatever they want to do with that object. The statement lock (status) in no way protects the status instance. However, if any of the threads tries to execute lock (status) they will block until the main thread releases the lock.

Using two separate object instances to lock can lead to deadlock. Assume one thread executes the following code:

lock (status) {
  ...
  lock (clients) {
    ...
  }

}

Another thread executes the following code where the locks are acquired in the reverse sequence:

lock (clients) {
  ...
  lock (status) {
    ...
  }

}

If the first thread manages to get the status first and the second the clients lock first they are deadlocked and both threads will no longer run.

In general I would advice you to encapsulate your shared state in a separate class and make access to it thread safe:

class State {

  readonly Object locker = new Object();

  public void ModifyState() {
    lock (this.locker) {
      ...
    }
  }

  public String AccessState() {
    lock (this.locker) {
      ...
      return ...
    }
  }

}

You can also mark you methods with the [MethodImpl(MethodImpl.Synchronized)] attribute, but it has its pitfalls as it will surround the method with a lock (this) which in general isn't recommended.

If you want to better understand what is going on behind the scenes of the lock statement you can read the Safe Thread Synchronization article in MSDN Magazine.

Martin Liversage
Edited the question to hopefully clarify my wording. I forgot to say that any other code which modifies my `status` object will acquire a lock on it first. Anyway that answers my question, thanks.
jnylen
A question, though: you say "you can't pass locks on to other threads." But as a contrived example, say I did `lock(someObject) { Thread t = new Thread(new ThreadStart(doSomething)); t.Start(); t.Join(); }` - then the lock would effectively be passed on to my other thread since it would be held the whole time that thread was running, right?
jnylen
@jnylen: I've removed the text you are quoting from my answer since it wasn't very meaningful. With regard to your example: The answer is yes as long as the new thread doesn't try to `lock (someObject)`. Otherwise you have a deadlock where both threads are blocked waiting for the other thread.
Martin Liversage
A: 

The locks certainly don't "expire" on their own, the lock will be valid until the closing brace of the lock(..){} statement.

Grzenio
"Expire" was a bad choice of words.
jnylen