xinthose
xinthose

Reputation: 3820

C++ boost::thread that never quits

My int main uses a while (1) loop to run my code. If I want to start continuous threads before I enter my while loop, would it look like this?

int main ()
{
     boost::thread_group threads;
     threads.create_thread (check_database);
     while (1)
     {
          // main program
     }
}

void check_database_and_plc ()
{
     while (1)
     {
          // check database, and if it needs to take action, do so;
          // this function / thread will never stop;
          // it will continuously check a single value from mysql and take
          // action based on that number (if 1, write to PLC, if 2, change
          // screens, etc);
          // also check plc for any errors, if there are any, tell int main
     }
}

Therefore I have two while loops running at the same time. Is there a better way to do this? Thank you for your time.

Upvotes: 1

Views: 331

Answers (1)

Yellows
Yellows

Reputation: 723

From you comment, I would (as a first try!) understand you need something like this:

bool plc_error = false;
boost::condition_variable cv;
boost::mutex mutex;
int main ()
{
     boost::thread_group threads;
     threads.create_thread (check_database);
     while (1)
     {

          boost::mutex::scoped_lock lock(mutex);
          while(!plc_error)
              cv.wait(lock);
          // deal with the error
          plc_error = false;
     }
}

void check_database_and_plc ()
{
     while (1)
     {
          // sleep a bit to ensure main will not miss notify_one()
          // check database and plc
          if (error){
              plc_error = true;
              cv.notify_one();
          }
     }
}

I did not take into account terminating and joining the thread into main, but the links I gave in the comments should help you.

Upvotes: 2

Related Questions