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 7602621
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T23:27:33+00:00 2026-05-30T23:27:33+00:00

I want to implement a message queue for 2 threads. Thread #1 will pop

  • 0

I want to implement a message queue for 2 threads. Thread #1 will pop the messages in queue and process it. Thread #2 will push the messages into queue.

Here is my code:

 Thread #1 //Pop message and process
 {
    while(true)
    {
        Lock(mutex);
        message = messageQueue.Pop();
        Unlock(mutex);

        if (message == NULL) //the queue is empty
        {
           //assume that the interruption occurs here (*)
            WaitForSingleObject(hWakeUpEvent, INFINITE);
            continue;
        }
        else
        {
            //process message
        }
    }
}

Thread #2 //push  new message in queue and wake up thread #1
{
    Lock(mutex);
    messageQueue.Push(newMessage)
    Unlock(mutex);

    SetEvent(hWakeUpEvent);
}

The problem is there are some cases SetEvent(hWakeUpEvent) will be called before WaitForSingleObject() ( note (*) ), it will be dangerous.

  • 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-30T23:27:34+00:00Added an answer on May 30, 2026 at 11:27 pm

    Your code is fine!

    There’s no actual problem with timing between SetEvent and WaitForSingleObject: the key issue is that WaitForSingleObject on an event will check the state of the event, and wait until it is triggered. If the event is already triggered, it will return immediately. (In technical terms, it’s level-triggered, not edge-triggered.) This means that it’s fine if SetEvent is called either before or during the call to WaitForSingleObject; WaitForSingleObject will return in either case; either immediately or when SetEvent is called later on.

    (BTW, I’m assuming using an Automatic Reset event here. I can’t think of a good reason for using a Manual Reset event; you’d just end up having to call ResetEvent immediately after WaitForSingleObject returns; and there’s a danger that if your forget this, you could end up Waiting for an event you’ve already waited for but forgotten to clear. Additionally,it’s important to Reset before checking the underlying data state, otherwise if SetEvent is called between when the data is processed and Reset() is called, you lose that information. Stick with Automatic Reset, and you avoid all this.)

    —

    [Edit: I misread the OP’s code as doing a single ‘pop’ on each wake, rather than only waiting on empty, so the comments below refer to code that scenario. The OP’s code is actually equivalent to the second suggested fix below. So the text below is really describing a somewhat common coding error where events are used as through they were semaphores, rather than the OP’s actual code.]

    But there is a different problem here [or, there would be if there was only one pop per wait…], and that’s that Win32 Events objects have only two states: unsignaled and signaled, so you can use them only to track binary state, but not to count. If you SetEvent and event that’s already signaled, it remains Signaled, and the information of that extra SetEvent call is lost.

    In that case, what could happen is:

    • Item is added, SetEvent called, event is now signaled.
    • Another item is added, SetEvent is called again, event stays signaled.
    • Worker thread calls WaitForSingleObject, which returns, clearing the event,
    • only one item is processed,
    • worker thread calls WaitForsingleObject, which blocks because the event is unsignaled, even though there’s still an item in the queue.

    There’s two ways around this: the classic Comp.Sci way is to use a semaphore instead of an event – semaphores are essentially events that count up all the ‘Set’ calls; you could conversely think of an event as a semaphore with a max count of 1 which ignores any other signals beyond that one.

    An alternative way is to continue using events, but when the worker thread wakes up, it can only assume that there may be some items in the queue, and it should attempt to process them all before it returns to waiting – typically by putting the code that pops the item in a loop that pops items and processes them until its empty. The event is now used not to count, but rather to signal “the queue is no longer empty”. (Note that when you do this, you can also get cases where, while processing the queue, you also process an item that was just added and for which SetEvent was called, so that when the worker thread reaches WaitForSingleObject, the thread wakes up but finds the queue is empty as the item has already been processed; this can seem a bit surprising at first, but is actually fine.)

    I view these two as mostly equivalent; there’s minor pros and cons to both, but they’re both correct. (Personally I prefer the events approach, since it decouples the concept of “something needing to be done” or “more data is available” from the quantity of that work or data.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to implement a JMS Queue to ensure that each message is only
We want to implement a News feed where a user can see messages broadcasted
Is it possible to implement text message compression on publishing to a queue/topic(with out
I want to implement a simple class for logging from multiple threads. The idea
I want to implement some kind of message bus in one of my Scala
The problem: I want to be able to FIFO queue outgoing messages. For update/deletion
I want to implement there is one thread for each connected session in a
I want implement in my software solution an VBA editor but in c# 3.0.
given this class definition: public class Frame { IFrameStream CapturedFrom; } I want implement
Microsoft has announce that WindowsLiveID become a OpenID provider . I want implement it

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.