永不退出的 C++ boost::thread
C++ boost::thread that never quits
我的 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 循环 运行ning。有一个更好的方法吗?感谢您的时间。
从你的评论中,我会(作为第一次尝试!)明白你需要这样的东西:
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
,但我在评论中提供的链接应该对您有所帮助。
我的 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 循环 运行ning。有一个更好的方法吗?感谢您的时间。
从你的评论中,我会(作为第一次尝试!)明白你需要这样的东西:
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
,但我在评论中提供的链接应该对您有所帮助。