Home All Groups Group Topic Archive Search About

Re: framework 1.1 & Queue class

Author
24 Apr 2007 1:18 PM
Brian Gideon
On Apr 24, 4:34 am, Hermit Dave <herm...@newsgroup.nospam> wrote:
Show quote
> I have modified the code to use a local syncronized wrapper as below. Will
> this work without thread concurrency issues in a multi threaded environment ?:
>
> private static Queue oQueue = null;
> private static bool bContinue = true;
>
> public static void Main()
> {
>         oQueue = new Queue();
>
>         Thread oThread1 = new Thread(new ThreadStart(WriteQueue));
>         Thread oThread2 = new Thread(new ThreadStart(ReadQueue));
>         oThread1.Start();
>         oThread2.Start();
>
> }
>
> private static void ReadQueue()
> {
>         Queue localQueue = Queue.Synchronized(oQueue);
>         while(true)
>         {
>                if(localQueue.Count > 0)
>                {
>                 int nValue = (int)localQueue.Dequeue();
>                 Console.WriteLine("Read from Queue: {0}", nValue);
>                }
>         }
>
> }
>
> private static void WriteQueue()
> {
>         Queue localQueue = Queue.Synchronized(oQueue);
>
>         for(int i = 1; i < 100; i++)
>         {
>                 localQueue.Enqueue(i);
>                 Console.WriteLine("Writing to Queue: {0}", i);
>         }
>         bContinue = false;}
>
> --
> Regards,
>

It looks okay to me, but that's only because there's one reader.  If
there are two or more readers then there will be race when the Count
property is checked and when the Dequeue happens.

AddThis Social Bookmark Button