Thread: lock needed in this scenario?

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    1,579

    lock needed in this scenario?

    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 after insertion process, so that the new produced Dic2 instance could be processed by the first thread by the name of Dic1.

    (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:
    // Thread 2
    Dictionary Dic2 = new Dictionary();
    Dic2.insert();
    Dic2.insert();
    Dic2.insert();
    lock (Dic1) // need lock here?
    {
    Dic1 = Dic2;
    } // end of lock

    thanks in advance,
    George

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    A lock is not needed, but you need to change the code of thread 1:
    Code:
    Dictionary mydic = Dic1;
    mydic.op1();
    ...
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 33
    Last Post: 05-14-2009, 10:15 AM
  2. read write lock in C#
    By George2 in forum C# Programming
    Replies: 0
    Last Post: 04-16-2008, 08:49 AM
  3. Atomic Operations
    By Elysia in forum Windows Programming
    Replies: 27
    Last Post: 03-27-2008, 02:38 AM
  4. nested lock?
    By George2 in forum C# Programming
    Replies: 2
    Last Post: 03-23-2008, 08:33 AM
  5. Threading and mutex's
    By megatron09 in forum C++ Programming
    Replies: 14
    Last Post: 09-07-2006, 02:40 PM