我的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循环同时运行。有一个更好的方法吗?感谢您的时间。
答案 0 :(得分:2)
从你发表评论,我会(作为第一次尝试!)理解你需要这样的东西:
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
,但我在评论中提供的链接应该对您有帮助。