George George

George George

  • NA
  • 778
  • 0

lock needed in this scenario?

May 25 2008 8:25 AM

Hello everyone,


I have the following scenario, and my question is whether I need to add lock or not?

In my scenario, there are two threads, one thread is accessing Dictionary instance Dic1, and the other thread is creating new Dictionary instance regularly in some interval, and the new Dictionary instance is named Dic2, and this thread will assign the instance pointed by Dic1 to Dic2, so that the new produced Dic2 could be processed by the first thread.

(Dic1 is like data consumer, and Dic2 is like data producer.)

1.

My question is whether I need lock for the operation for Dic1 of thread1, and Dic2 to Dic1 assignment operation in thread 2?

2.

Beyond using lock, are there any more efficient method? e.g. less locking? or not using lock at all?

Some pesudo code,

[Code]
// Thread 1
lock (Dic1) // lock for Dic1 instance needed here? This is my question
{
Dic1.op1();
Dic1.op2();
Dic1.op3();
} // end of lock
[/Code]

[Code]
// Thread 2
Dictionary Dic2 = new Dictionary();
Dic2.insert();
Dic2.insert();
Dic2.insert();
lock (Dic1) // need lock here?
{
Dic1 = Dic2;
} // end of lock
[/Code]


thanks in advance,
George


Answers (2)