C++ C++;boost::永不退出的线程

C++ C++;boost::永不退出的线程,c++,multithreading,boost,C++,Multithreading,Boost,我的int main使用while(1)循环来运行代码。如果我想在进入while循环之前启动连续线程,它会像这样吗 int main () { boost::thread_group threads; threads.create_thread (check_database); while (1) { // main program } } void check_database_and_plc () { whi

我的int main使用while(1)循环来运行代码。如果我想在进入while循环之前启动连续线程,它会像这样吗

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
     }
}
因此,我有两个while循环同时运行。有更好的方法吗?谢谢你抽出时间

从你的评论中,我(作为第一次尝试!)理解你需要这样的东西:

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();
          }
     }
}

我没有考虑终止线程并将其连接到
main
,但是我在评论中给出的链接应该可以帮助您。

看起来不错。不过,您可能需要添加一些中断/停止条件。不要忘记正确保护数据库,这样对它的访问(读/写)是线程安全的。编辑:仔细想想,如果数据库中的更改是由
main
中的某些特定操作引起的,您可以使用
signal()
wait()
方法来防止
check\u database()
在不需要时使用CPU。我该如何确切地做到这一点?@sinthose:related links:;看看我的答案。如果不符合您的要求,可以进一步询问。为什么要混合使用DB和PLC检查?我会将其移动到两个线程中,这样您也可以更自由地配置检查之间的间隔。不客气。这在多线程编程中很常见——我建议您阅读一些关于这个主题的理论(关键词:线程、同步、互斥、信号量、条件变量或某些操作系统课程/教科书),它将为您提供最佳解决问题的工具。这非常重要,因为并发编程远不如串行(常规?)编码直观。因此,如果在int main的while(1)循环中的任何一点,plc_错误为true,它将立即转到第二个while(!plc_error)循环,处理错误,将其设回false,然后继续while(1)循环?否。
检查()
线程将向等待通知的任何其他线程发送“通知”,然后继续执行。由于这里只有两个线程,它将“唤醒”
main()
线程,该线程在收到消息之前一直处于休眠状态。