使用 boost:thread 的可运行类
Runnable class using boost:thread
编辑> 本教程提供了一个很好的答案
如何使用boost::thread
使类可运行?
class Hello
{
void run();
bool canRun();
boost::condition_variable cond;
boost::mutex mut;
};
Hello::run()
{
boost::unique_lock<boost::mutex> lock(this->mut);
while (!this->canRun())
this->cond.wait(lock);
// do my stuff
}
我不知道我是否应该继承boost::thread
,在我的类中有一个boost::thread
属性......
我希望能够这样做:
Hello hello = Hello();
hello.run();
hello.stop();
我认为你应该在你的类中放一个线程实例,在你的 run() 方法中你可以启动线程(当然使用另一个成员函数)。 在 stop() 中,你可以在设置 canRun = false
后调用 thread::join()。
我会
说,为什么不:)在科里鲁现场观看
它与 c++03 兼容。
#include <boost/thread.hpp>
struct Hello
{
void run();
bool canRun() { return true; }
boost::condition_variable cond;
boost::mutex mut;
};
void Hello::run()
{
boost::unique_lock<boost::mutex> lock(this->mut);
cond.wait(lock, boost::bind(&Hello::canRun, this));
std::cout << "Done";
}
int main()
{
Hello obj;
boost::thread th(&Hello::run, &obj);
boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
{
boost::lock_guard<boost::mutex> lk(obj.mut);
obj.cond.notify_one();
}
th.join();
}
请注意,我使用了 wait()
的谓词版本来等待启动条件。
相关文章:
- 运行同一解决方案的另一个项目的项目
- 在运行之前获取 std::thread's thread:id?
- CLang:在 std::thread 中运行函数会导致结构创建BAD_ACCESS
- 如何使用boost.thread运行多个接收器,每个线程应该分配给每个接收器?
- 使用 vector<thread> 和 .join() 未并行运行的多线程C++程序
- 使用 boost::thread 运行函子,但析构函数被错误地调用
- 移动包含正在运行的 std::thread 成员的对象
- 如何使用 Thread 运行类构造函数
- C++11使用std::thread运行模板化类函数
- boost::thread应该在无限循环中运行,并等待没有互斥锁的新输入
- Linux gnu++11,在运行时获取"Enable multithreading to use std::thread: Operation not permitted"
- 在 Linux 上使用 GCC 4.6 和 4.7 运行简单 std::thread 代码时的核心转储
- 我的'show progress thread'在计数时无法运行
- 使用std::thread的C++多线程应用程序在Windows上运行良好,但在Ubuntu上则不然
- 检查std::thread是否仍在运行
- 终止运行线程c++ std::thread
- 为什么std::thread采用函数由右值运行
- 使用 boost:thread 的可运行类
- 使用Boost Thread在具有不同输入的多个线程上运行一个函数
- std::thread -如何使主线程继续运行,子线程分支