gpt4 book ai didi

C++11:类中的 std::thread 在构造函数中执行具有线程初始化的函数成员

转载 作者:IT老高 更新时间:2023-10-28 22:33:47 31 4
gpt4 key购买 nike

我正在尝试使用 C++11 中的 std::thread。如果可以在执行其函数成员之一的类中拥有 std::thread ,我无法找到任何地方。考虑下面的例子......在我的尝试中(如下),函数是 run()。

我使用带有 -std=c++0x 标志的 gcc-4.4 进行编译。

#ifndef RUNNABLE_H
#define RUNNABLE_H

#include <thread>

class Runnable
{
public:
Runnable() : m_stop(false) {m_thread = std::thread(Runnable::run,this); }
virtual ~Runnable() { stop(); }
void stop() { m_stop = false; m_thread.join(); }
protected:
virtual void run() = 0;
bool m_stop;
private:
std::thread m_thread;
};


class myThread : public Runnable{
protected:
void run() { while(!m_stop){ /* do something... */ }; }
};

#endif // RUNNABLE_H

我收到此错误和其他错误:(使用和不使用 $this 时出现相同的错误)

Runnable.h|9|error: no matching function for call to ‘std::thread::thread(<unresolved overloaded function type>, Runnable* const)’|

传递指针时。

Runnable.h|9|error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&Runnable::run’|

最佳答案

这里有一些代码需要仔细考虑:

#ifndef RUNNABLE_H
#define RUNNABLE_H

#include <atomic>
#include <thread>

class Runnable
{
public:
Runnable() : m_stop(), m_thread() { }
virtual ~Runnable() { try { stop(); } catch(...) { /*??*/ } }

Runnable(Runnable const&) = delete;
Runnable& operator =(Runnable const&) = delete;

void stop() { m_stop = true; m_thread.join(); }
void start() { m_thread = std::thread(&Runnable::run, this); }

protected:
virtual void run() = 0;
std::atomic<bool> m_stop;

private:
std::thread m_thread;
};


class myThread : public Runnable
{
protected:
void run() { while (!m_stop) { /* do something... */ }; }
};

#endif // RUNNABLE_H

一些注意事项:

  • 声明 m_stop作为一个简单的bool像你一样是可怕的不足;阅读内存障碍
  • std::thread::join可以在没有 try..catch 的情况下调用它来自析构函数是鲁莽的
  • std::threadstd::atomic<>是不可复制的,所以 Runnable应该这样标记,如果没有其他原因,只是为了避免 VC++ 的 C4512 警告

关于C++11:类中的 std::thread 在构造函数中执行具有线程初始化的函数成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5956759/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com