Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 702301
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T03:42:20+00:00 2026-05-14T03:42:20+00:00

I have two threads, one thread processes a queue and the other thread adds

  • 0

I have two threads, one thread processes a queue and the other thread adds stuff into the queue.

  1. I want to put the queue processing thread to sleep when its finished processing the queue
  2. I want to have the 2nd thread tell it to wake up when it has added an item to the queue

However these functions call System.Threading.SynchronizationLockException: Object synchronization method was called from an unsynchronized block of code on the Monitor.PulseAll(waiting); call, because I havent synchronized the function with the waiting object. [which I dont want to do, i want to be able to process while adding items to the queue]. How can I achieve this?

Queue<object> items = new Queue<object>();
object waiting = new object();

1st Thread

public void ProcessQueue()
{
 while (true)
 {
   if (items.Count == 0)
     Monitor.Wait(waiting);

    object real = null;
    lock(items) {
    object item = items.Dequeue();
    real = item;
    }
    if(real == null)
        continue;
    .. bla bla bla
 } 
}

2nd Thread involves

public void AddItem(object o)
{
 ... bla bla bla
 lock(items)
 {
 items.Enqueue(o);
 }
 Monitor.PulseAll(waiting);
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T03:42:20+00:00Added an answer on May 14, 2026 at 3:42 am

    If you have access to .NET 4.0, what you want to do can be achieved by BlockingCollection<T>.
    If you want to do it yourself by means of the Monitor class and signaling with Pulse(), you are actually on the right track.
    You get the exception because to call Wait(), Pulse() and PulseAll(), you have to own the lock on the specified object. You happen to miss this on waiting.

    A sample basic thread-safe queue that can be used:

    • with foreach on the consumer,
    • with while or your favorite conditional construct on the producer side,
    • handles multiple producers/consumers and
    • uses lock(), Monitor.Pulse(), Monitor.PulseAll() and Monitor.Wait():

    .

    public class SignaledQueue<T>
    {
        Queue<T> queue = new Queue<T>();
        volatile bool shutDown = false;
    
        public bool Enqueue(T item)
        {
            if (!shutDown)
            {
                lock (queue)
                {
                    queue.Enqueue(item);
                    //Pulse only if there can be waiters.
                    if (queue.Count == 1)
                    {
                        Monitor.PulseAll(queue);
                    }
                }
                return true;
            }
            //Indicate that processing should stop.
            return false;
        }
    
        public IEnumerable<T> DequeueAll()
        {
            while (!shutDown)
            {
                do
                {
                    T item;
                    lock (queue)
                    {
                        //If the queue is empty, wait.
                        if (queue.Count == 0)
                        {
                            if (shutDown) break;
                            Monitor.Wait(queue);
                            if (queue.Count == 0) break;
                        }
                        item = queue.Dequeue();
                    }
                    yield return item;
                } while (!shutDown);
            }
        }
    
        public void SignalShutDown()
        {
            shutDown = true;
            lock (queue)
            {
                //Signal all waiting consumers with PulseAll().
                Monitor.PulseAll(queue);
            }
        }
    
    }
    

    Sample usage:

    class Program
    {
        static void Main(string[] args)
        {
            int numProducers = 4, numConsumers = 2;
            SignaledQueue<int> queue = new SignaledQueue<int>();
    
            ParameterizedThreadStart produce = delegate(object obj)
            {
                Random rng = new Random((int)obj);
                int num = 0;
                while (queue.Enqueue(++num))
                {
                    Thread.Sleep(rng.Next(100));
                } 
            };
    
            ThreadStart consume = delegate
            {
                foreach (int num in queue.DequeueAll())
                {
                    Console.Write(" {0}", num);
                }
            };
    
            Random seedRng = new Random();
            for (int i = 0; i < numProducers; i++)
            {
                new Thread(produce).Start(seedRng.Next());
            }
    
            for (int i = 0; i < numConsumers; i++)
            {
                new Thread(consume).Start();
            }
    
            Console.ReadKey(true);
            queue.SignalShutDown();
    
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 367k
  • Answers 367k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The name is a bit misleading - the MP3 playing… May 14, 2026 at 4:46 pm
  • Editorial Team
    Editorial Team added an answer This is overflow, your professor is correct. You are storing… May 14, 2026 at 4:46 pm
  • Editorial Team
    Editorial Team added an answer The javadoc for each method says what it's been replaced… May 14, 2026 at 4:46 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.