我有一个类,它当前使用一个类方法作为线程主体:
class Something {
public:
bool isRunning() { return m_run; }
private:
void threadBody(void);
std::unique_ptr<std::thread> m_thread;
std::atomic<bool> m_run;
};除了上面简单的示例之外,该类还有更多内容,当前的代码如下所示:
Something::Something() : m_run(true) {
m_thread = std::make_unique<std::thread>(std::bind(&Something::threadBody, this));
}类方法"threadBody“如下所示:
void Something::threadBody(void) {
while( m_run ) {
//Do something here until m_run is false
}
}现在我被要求将线程体转换为Lambda,我正在阅读如何做到这一点,并寻求帮助我如何实现同样的。
如何传递类的实例,以便可以在线程的主体中访问其成员?
这是对的吗?
m_thread = std::make_unique<std::thread>([this](Something* pInstance) {
while( pInstance->isRunning ) {
//Do something here until m_run is false
}
});发布于 2020-05-12 11:30:57
您不需要这个参数--您正在捕获this,并且由于lambda是在类的范围中定义的,所以在成员定义中有正常的可访问性:
[this]() {
while (m_run) {
// ...
}
}发布于 2020-05-12 11:25:51
如果您已经捕获了"this“参数,则不需要显式地将其作为参数传递。不知道为什么你需要它成为unique_ptr。
更简单:
class Something {
...
std::thread m_thread;
};构造者:
Something::Something() : m_run(true) {
m_thread = std::thread([this]() {
while (isRunning()) {
// Do Something
}
});
}发布于 2020-05-12 11:32:47
听起来你想取消这门课。我想我会提出如下建议:
std::atomic<bool> finish{false};
std::thread t1 {[&finish]() {
unsigned counter = 0;
while (!finish) {
std::cout << "Run " << counter++ << "\n";
std::this_thread::sleep_for(100ms);
}
}};
std::this_thread::sleep_for(1s);
finish = true;
t1.join(); 在此,我作了两个重要的改动:
atomic<bool>标志使用finish loop以避免不安全的线程行为。下面是一个活生生的例子。
https://stackoverflow.com/questions/61750272
复制相似问题