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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T11:58:08+00:00 2026-05-12T11:58:08+00:00

I have the following code: class TimeOutException {}; template <typename T> class MultiThreadedBuffer {

  • 0

I have the following code:

class TimeOutException
{};

template <typename T>
class MultiThreadedBuffer
{
public:
    MultiThreadedBuffer()
    {
        InitializeCriticalSection(&m_csBuffer);
        m_evtDataAvail = CreateEvent(NULL, TRUE, FALSE, NULL);
    }
    ~MultiThreadedBuffer()
    {
        CloseHandle(m_evtDataAvail);
        DeleteCriticalSection(&m_csBuffer);
    }
    void LockBuffer()
    {
        EnterCriticalSection(&m_csBuffer);
    }
    void UnlockBuffer()
    {
        LeaveCriticalSection(&m_csBuffer);
    }
    void Add(T val)
    {
        LockBuffer();
        m_buffer.push_back(val);
        SetEvent(m_evtDataAvail);
        UnlockBuffer();
    }
    T Get(DWORD timeout)
    {
        T val;
        if (WaitForSingleObject(m_evtDataAvail, timeout) == WAIT_OBJECT_0) {
            LockBuffer();

            if (!m_buffer.empty()) {
                val = m_buffer.front();
                m_buffer.pop_front();
            }

            if (m_buffer.empty()) {
                ResetEvent(m_evtDataAvail);
            }

            UnlockBuffer();
        } else {
            throw TimeOutException();
        }
        return val;
    }
    bool IsDataAvail()
    {
        return (WaitForSingleObject(m_evtDataAvail, 0) == WAIT_OBJECT_0);
    }
    std::list<T> m_buffer;
    CRITICAL_SECTION m_csBuffer;
    HANDLE m_evtDataAvail;
};

Unit testing shows that this code works fine when used on a single thread as long as T’s default constructor and copy/assignment operators don’t throw. Since I’m writting T, that is acceptable.

My problem is the Get method. If there is no data available (i.e. m_evtDataAvail is not set), then a couple of threads can block on the WaitForSingleObject call. When new data becomes available, they all fall through to the Lock() call. Only one will pass and can get the data out and move on. After the Unlock() another thread can move on through and will find that there is no data. Currently it will return the default object.

What I want to happen is for that second thread (and others) to go back to the WaitForSingleObject call. I could add an else block that unlocked and did a goto but that just feels evil.

That solution also adds the possibility for an endless loop since each trip back would restart the timeout. I could add some code to check the clock on entry and adjust the timeout on each trip back but then this simple Get method starts to get very complicated.

Any ideas on how to solve these problems while maintaining testability and simplicity?

Oh, for anyone wondering, the IsDataAvail function only exists for testing. It won’t be used in production code. The Add and Get are the only methods that will be used in a non-testing environment.

  • 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-12T11:58:08+00:00Added an answer on May 12, 2026 at 11:58 am

    You need to create a auto-reset event instead of a manual reset event. This guarantees that if multiple threads are waiting on an event, and when the event is set only one thread will be released. All other threads will remain in waiting state. You can create auto-reset event by passing FALSE to the second parameter of CreateEvent API. Also, note that this code is not exception safe i.e. after locking the buffer, if some statement throws an exception your critical section will not be unlocked. Use RAII principle to ensure that your critical section gets unlocked even in the case of exceptions.

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

Sidebar

Ask A Question

Stats

  • Questions 202k
  • Answers 202k
  • 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 exception you got says pretty much it all: in… May 12, 2026 at 8:23 pm
  • Editorial Team
    Editorial Team added an answer itertools.product(*A) For more details check the python tutorial May 12, 2026 at 8:23 pm
  • Editorial Team
    Editorial Team added an answer No, the splashscreen class in WPF only works with images.… May 12, 2026 at 8:23 pm

Related Questions

I've created a Windows Communication Foundation service (the appDomain in this case is a
I have the following code: class IncidentTag: def __init__(self,tag): self.tag = tag def equals(self,obj):
I have the following code class Program { static void Main(string[] args) { List<A>
I have the following code: class SuperClass { public static String getName() { return

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.