【发布时间】:2015-11-23 17:34:11
【问题描述】:
我有 C# 编码经验;我开始学习 C++ 并使用 boost 库进行线程处理。 我编写了以下类 - 尝试将成员函数作为线程执行。编写以下简单代码,我希望线程函数内的 while 循环每秒执行一次。
#include <boost/chrono/chrono.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>
using namespace boost;
class MyClassWithThread : public boost::enable_shared_from_this<MyClassWithThread>
{
mutex muThreadControl;
condition_variable cvThreadControl;
bool threadToBeStopped = false;
void ThreadFunction()
{
std::cout << "Beginning the Thread" << std::endl;
while(true)
{
bool endIOThread = false;
std::cout << "\nChecking if Thread to be stopped: ";
{
boost::mutex::scoped_lock lock(muThreadControl);
endIOThread = cvThreadControl.wait_for(lock,
boost::chrono::seconds(1),
[this]{return threadToBeStopped;} ) == cv_status::no_timeout;
std::cout << endIOThread << std::endl
}
}
std::cout << "Exiting the Thread" << std::endl;
}
public:
thread threadRunner;
MyClassWithThread()
{
threadRunner = thread(&MyClassWithThread::ThreadFunction, this);
}
};
int main(int argc, char* argv[])
{
MyClassWithThread myclassWithThread;
myclassWithThread.threadRunner.join();
return 0;
}
在 Linux 上构建:
g++ -std=c++11 -pthread cond-wait-test.cpp -o cond-wait-test -lboost_system -lboost_thread -lboost_chrono
但是,当我执行代码时,我只注意到线程执行在调用 wait_for 方法时被阻塞;永远。尽管有超时时间。此外,系统的资源监视器显示处理器内核正在 100% 使用。
谁能解释一下代码中发生了什么?
【问题讨论】:
-
看起来没有任何东西可以退出您的 while 循环。
-
如果它使用 100% CPU 那么它不会被阻塞。谓词检查或超时一定有问题。
-
@MohamadElghawi,上面的代码用于测试目的;我希望控制台打印:检查线程是否停止:0 检查线程是否停止:0 检查线程是否停止:0...
-
@ZanLynx,100% CPU 利用率不是预期的迹象,因为我希望它只等待一秒钟(睡眠)。根本不应该消耗任何CPU..
-
@rat6:既然它对我有用,也许你需要包括你的编译器、操作系统和 Boost 版本的详细信息。
标签: c++ multithreading boost