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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T01:23:37+00:00 2026-06-10T01:23:37+00:00

I’m writing a program in C++. I’ve noticed that it’s gaining a number of

  • 0

I’m writing a program in C++. I’ve noticed that it’s gaining a number of threads whose purpose is to do something at intervals, there are 3 or 4 of them. I decided to refactor by writing a scheduler service that the other places that use these threads could subscribe to, which should reduce the number of extra event threads I have running at any time to just one.

I don’t have any code that uses this yet; before I start writing it I’d like to know if it’s possible, and get some feedback on my design. A brief description of what I’d like to accomplish is this:

To add an event

  1. Caller provides an event and a schedule
  2. Schedule provides the next occurrence of the event
  3. (event, schedule) pair is added to an event queue
  4. interrupt sleeping event thread (i.e. wake it up)

The event thread main loop

  1. try to get the next event in the event queue
  2. If there is no pending event, go straight to 4
  3. Get the time that the next event is supposed to occur
  4. Sleep until next event (or forever if no waiting event)
  5. If sleeping was interrupted for any reason, loop back to 1
  6. If sleeping completed successfully, perform current event
  7. Update queue (remove event, re-insert if it’s a repeating event)
  8. Jump back to 1

I’ve done a bit of research and know that it’s possible to interrupt a sleeping thread, and I believe that as long as simultaneous access to the event queue is prevented, there shouldn’t be any dangerous behavior. I’d imagine that waking a thread HAS to be possible, java’s Thread’s sleep() call throws an InterruptedException under some circumstances, and unless it doesn’t rely on the operating system’s underlying sleep call, it’s got to be possible somehow.

Question

Can anyone comment on my approach? Is this a wheel I’d be better off not reinventing? How, specifically, can you interrupt a sleeping thread such that execution resumes at the next instruction, and is it possible to detect this from the interrupted thread?

A note about boost

I’d bet you can write a scheduler with boost, but this compiles and runs on a machine that’s, for lack of a better phrase, a load of crap. I’ve compiled boost programs before on it, and each file that pulls boost in usually takes upwards of 30 seconds to compile. If I can avoid this irritating development obstacle, I’d very much like to.

Addendum – Working Code [Amended as per caf’s suggestion]

This is the code I’ve produced that works. It’s been rudimentarily tested but has properly handled both single and repeated events with varying delays.

Here’s the event thread’s body:

void Scheduler::RunEventLoop()
{
    QueueLock();                   // lock around queue access
    while (threadrunning)
    {
        SleepUntilNextEvent();     // wait for something to happen

        while (!eventqueue.empty() && e.Due())
        {                          // while pending due events exist
            Event e = eventqueue.top();
            eventqueue.pop();

            QueueUnlock();         // unlock
            e.DoEvent();           // perform the event
            QueueLock();           // lock around queue access

            e.Next();              // decrement repeat counter
                                   // reschedule event if necessary
            if (e.ShouldReschedule()) eventqueue.push(e);
        }
    }
    QueueUnlock();                 // unlock
    return;                        // if threadrunning is set to false, exit
}

Here’s the sleep function:

void Scheduler::SleepUntilNextEvent()
{
    bool empty = eventqueue.empty();  // check if empty

    if (empty)
    {
        pthread_cond_wait(&eventclock, &queuelock); // wait forever if empty
    }
    else
    {
        timespec t =                  // get absolute time of wakeup
            Bottime::GetMillisAsTimespec(eventqueue.top().Countdown() + 
                                         Bottime::GetCurrentTimeMillis());
        pthread_cond_timedwait(&eventclock, &queuelock, &t); // sleep until event
    }
}

Finally, AddEvent:

void Scheduler::AddEvent(Event e)
{
    QueueLock();
    eventqueue.push(e);
    QueueUnlock();
    NotifyEventThread();
}

Relevant variable declarations:

bool threadrunning;
priority_queue<Event, vector<Event>, greater<Event> > eventqueue;
pthread_mutex_t queuelock; // QueueLock and QueueUnlock operate on this
pthread_cond_t eventclock;

To deal with the issue of generic events, each Event contains a pointer to an object of abstract type action, whos subclasses override action::DoEvent. this method is called from inside Event::DoEvent. actions are ‘owned’ by their events, i.e. they are automatically deleted if the event no longer needs to be rescheduled.

  • 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-06-10T01:23:38+00:00Added an answer on June 10, 2026 at 1:23 am

    What you are looking for is pthread_cond_t object, pthread_cond_timedwait and pthread_cond_wait functions. You could create conditional variable isThereAnyTaskToDo and wait on it in event thread. When new event is added, you just wake event thread with pthread_cond_signal().

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

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I need a function that will clean a strings' special characters. I do NOT
I am writing an app with both english and french support. The app requests

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.