Thread: lock needed in this scenario?

  1. #1
    Registered User
    Join Date
    May 2006

    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.)


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


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

    Some pesudo code,

    // Thread 1
    lock (Dic1) // lock for Dic1 instance needed here? This is my question
    } // end of lock
    // Thread 2
    Dictionary Dic2 = new Dictionary();
    lock (Dic1) // need lock here?
    Dic1 = Dic2;
    } // end of lock

    thanks in advance,

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

    "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
Website Security Test