Results 1 to 7 of 7

Thread: Synchronize a producer thread and a consumer thread in C#

  1. #1
    Join Date
    Jul 2010
    Posts
    32

    Synchronize a producer thread and a consumer thread in C#

    I am having better knowledge of C# and now want to know how to synchronize the main thread and two worker threads using the lock keyword. I am having bit information about the lock keyword. The lock keyword ensures that a thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released. In general, avoid locking a public type, or instances beyond the control of your code. The current construction lock (this), lock (typeof (MyType)) and lock ("myLock") violate this directive:
    • lock (this) is problematic if it can be accessed publicly in the proceeding.
    • lock (typeof (MyType)) is problematic if it is possible to access publicly MyType.
    • lock ("myLock") is problematic since any other code in the process using the same channel share the same lock.
    Also according to me, the recommended method is to define a private object to lock, or a private static object variable to protect data common to all instances. But still not able to synchronize the producer thread with the consumer thread. Anyone over there can help me in this.???

  2. #2
    Join Date
    Mar 2008
    Posts
    227

    Re: Synchronize a producer thread and a consumer thread in C#

    The example creates two auxiliary threads, or threads active. One thread produces components and stores them in a generic queue that is not thread safe. The other thread consumes items from this queue. Moreover, the main thread displays the contents of the regular queue. Therefore, three threads can access the queue. The lock keyword is used to synchronize access to the queue to check the status of the queue is not damaged. Synchronization is provided by two additional event objects in addition to blocking access simultaneously with the lock keyword One is used to indicate the active threads to finish, and the other is used by the producer thread to signal the thread consumer when a new item was added to the queue. These two event objects are encapsulated in a class named SyncEvent. This allows events to be passed to objects that are easily threads consumer and producer. SyncEvent class is defined as follows:
    Code:
    public class SyncEvents
    {
        public SyncEvents()
        {
    
            _newItemEvent = new AutoResetEvent(false);
            _exitThreadEvent = new ManualResetEvent(false);
            _eventArray = new WaitHandle[2];
            _eventArray[0] = _newItemEvent;
            _eventArray[1] = _exitThreadEvent;
        }
    
        public EventWaitHandle ExitThreadEvent
        {
            get { return _exitThreadEvent; }
        }
        public EventWaitHandle NewItemEvent
        {
            get { return _newItemEvent; }
        }
        public WaitHandle[] EventArray
        {
            get { return _eventArray; }
        }
    
        private EventWaitHandle _newItemEvent;
        private EventWaitHandle _exitThreadEvent;
        private WaitHandle[] _eventArray;
    }

  3. #3
    Join Date
    Mar 2008
    Posts
    258

    Re: Synchronize a producer thread and a consumer thread in C#

    Class AutoResetEvent is used for "new matter" so that this event will reset automatically each time the consumer thread responds to this event. Class ManualResetEvent is also used for the event "exit" because you want multiple threads respond when this event is reported. If you tend to use AutoResetEvent , the event would return to a state not reported after a single thread has responded to the event. The other thread does not respond, and in this case would not end. Class SyncEvent creates two events and stores them in two different forms: EventWaitHandle , which is the base class for AutoResetEvent and ManualResetEvent and in a table based on WaitHandle . As you see in the section on consumer thread, this table is necessary so that the consumer thread can respond to either event. Consumer and producer threads are represented by the Producer and Consumer classes named. They define a method named ThreadRun. These methods are used as entry points for threads active than the Main method creates.

  4. #4
    Join Date
    Apr 2008
    Posts
    193

    Re: Synchronize a producer thread and a consumer thread in C#

    ThreadRun method defined by the Producer looks like this:

    Code:
    // Producer.ThreadRun
    public void ThreadRun()
    {
        int count = 0;
        Random r = new Random();
        while (!_syncEvents.ExitThreadEvent.WaitOne(0, false))
        {
            lock (((ICollection)_queue).SyncRoot)
            {
                while (_queue.Count < 20)
                {
                    _queue.Enqueue(r.Next(0,100));
                    _syncEvents.NewItemEvent.Set();
                    count++;
                }
            }
        }
        Console.WriteLine("Producer thread: produced {0} items", count);
    }
    This method moves in a loop until the event "exit thread" is reported. The status of this event is tested with the method WaitOne using the property defined by the class ExitThreadEvent SyncEvent. In this case, the state of the event is verified without blocking the current thread as the first argument used WaitOne is zero, indicating that the method should return immediately. If WaitOne returns true, the event in question is currently reported. If this is the case, the method returns ThreadRun, which has the effect of completing the current thread that runs it.

  5. #5
    Join Date
    Dec 2008
    Posts
    183

    Re: Synchronize a producer thread and a consumer thread in C#

    This method moves in a loop until the event "exit thread" is reported. The status of this event is tested with the method WaitOne using the property defined by the class ExitThreadEvent SyncEvent.
    Until the event "exit thread" is reported, the method Producer.ThreadStart tries to retain 20 items in the queue. An element is an integer between zero and 100. The collection must be locked before adding new elements to prevent consumer threads and the main thread to access simultaneously to the collection. This is done using the lock keyword. The argument passed to lock is field SyncRoot exposed through the interface ICollection. This field is provided specifically to synchronize access to the thread. Exclusive access to the collection is granted for all instructions in the next block of code lock. For each new element that the producer adds to the queue, a call to set the event "new element" is performed. This indicates that the consumer thread is suspended out of state to address the new element.

  6. #6
    Join Date
    Dec 2008
    Posts
    202

    Re: Synchronize a producer thread and a consumer thread in C#

    The Consumer object also defines a method called ThreadRun. As the producer ThreadRun version of this method is executed by an active thread created by the Main method. However, the consumer version of ThreadStart must meet two events. Consumer.ThreadRun method is as follows:

    Code:
    // Consumer.ThreadRun
    public void ThreadRun()
    {
        int count = 0;
        while (WaitHandle.WaitAny(_syncEvents.EventArray) != 1)
        {
            lock (((ICollection)_queue).SyncRoot)
            {
                int item = _queue.Dequeue();
            }
            count++;
        } 
        Console.WriteLine("Consumer Thread: consumed {0} items", count);
    }
    This method uses WaitAny consumer thread to block until the reporting of wait handles in the table provided. In this case, there are two handles in the array, to complete the active threads, and the other to indicate a new element was added to the collection. WaitAny returns the index of the event was reported . The event "new element" is the first table, an index of zero indicates a new element. In this case, look for an index of 1 indicates that the event "out of the thread. It can determine if this method continues to consume the items. If the event "new element" was mentioned, you get exclusive access to the collection with lock and consume the new item. Because this example produces and consumes thousands of items, you do not display all items consumed.

  7. #7
    Join Date
    Jan 2009
    Posts
    140

    Re: Synchronize a producer thread and a consumer thread in C#

    Note that the queue and the synchronization event object passed to threads Consumer and Producer as constructor arguments. This provides two objects that have shared resources to carry out their respective tasks. Two new objects Thread are then created, using the method ThreadRun, as arguments for each. Each worker thread, when it starts, uses this argument as an entry point for the thread. Second, hand throws the two worker threads with a call to start , such as:
    Code:
    producerThread.Start();
    consumerThread.Start();
    At this point, the two new threads are created and begin execution asynchronously, independently of the main thread that is currently running the Main method. In fact, Hand then interrupts the main thread with a call to Sleep. The method stops the thread currently running for a given number of milliseconds. After this interval, the Main method is reactivated and displays the contents of the queue. Main repeated this four times as follows:
    Code:
    for (int i=0; i<4; i++)
    {
        Thread.Sleep(2500);
        ShowQueueContents(queue);
    }
    Finally, Hand signals to active threads they must end by calling the Set Event "exit thread" and then uses the method Join each active thread on the main thread to block until each active thread respond to the event and ends.

Similar Threads

  1. Perl in the thread
    By Sydney_7 in forum Software Development
    Replies: 4
    Last Post: 04-03-2010, 03:57 AM
  2. Thread vs Process
    By ramsun in forum Software Development
    Replies: 5
    Last Post: 23-02-2010, 08:05 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,462,156.73090 seconds with 16 queries