Question

I'm new at .NET/Threads and I'd like to know if anyone can help me on this exercise. I need to replace the comments in order to make it work without locking the threads:

private Queue<int> queue;

public void ConsumeFunc(){
    while (true){
        // 1
        while (/* 2 */){
        // 3
        }
        int element = queue.Dequeue();
        // 4
        Console.WriteLine("Consume element: " + element);
        Thread.Sleep(new Random((int)DateTime.Now.Ticks).Next(0, 2) * 1000);
    }
}

private void ProduceFunc(){
    while (true) {
        // 1
        queue.Enqueue(DateTime.Now.Millisecond);
        // 2
        // 3
        Thread.Sleep(new Random((int)DateTime.Now.Ticks).Next(0, 2) * 1000);
    }
}

I managed this but it's not completed

public void ConsumerFunc(){
    while (true){
        Monitor.PulseAll(queue);    // 1
        while (queue.Count == 0){   /* 2 */
            Monitor.Wait(queue);    // 3
        }
        int element = queue.Dequeue();
        lock (queue)    // 4
        Console.WriteLine("Consume element: " + element);
        Thread.Sleep(new Random((int)DateTime.Now.Ticks).Next(0, 2) * 1000);
    }
}


public void ProducerFunc(){
    while (true) {
        lock (queue)    // 1
        queue.Enqueue(DateTime.Now.Millisecond);
        Monitor.PulseAll(queue);    // 2
        // 3 ???
        Thread.Sleep(new Random((int)DateTime.Now.Ticks).Next(0, 3) * 1000);
    }
}

and gives the following error: Object synchronization method was called from an unsynchronized block of code, on Monitor.PulseAll(queue);

Was it helpful?

Solution

Rather than fighting to implement the synchronization yourself, take a look at BlockingCollection. It handles all the synchronization for you, and will perform better than anything you can create using the Queue class and Monitor.

There are plenty of examples in the .NET documentation, here on Stack Overflow, and elsewhere. You might find my article useful: http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=821

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top