C++ 简单线程启动问题

标签 c++ pthreads

我的代码相当简单,而且我发现的每个示例看起来都非常相似。我确信我遗漏了一些基本的东西,所以我们将不胜感激任何帮助。

/*-------------------------------------
State
--------------------------------------*/
void Receiver::start(int num_threads = 1) {
    _kill_mtx.lock();
    _kill_state = false;
    _kill_mtx.unlock();
    for (int i=0; i<num_threads; ++i)
        threads.push_back(std::thread(thread_func));  // LINE 24

    std::cout << threads.size() << " now running.\n";
    std::cout << std::thread::hardware_concurrency() << " concurrent threads are supported.\n";
}

void Receiver::stop() {

}

/*-------------------------------------
Thread
--------------------------------------*/
void Receiver::thread_func() {
    while(true) {
        if (_kill_mtx.try_lock()) {
            if (_kill_state) {
                break;
            }
            _kill_mtx.unlock();
        }
        std::cout << "Still Alive!" << std::endl;
    }
}

使用 -std=c++0x -lstdc++ -ldbus-c++-1 -pthread 编译并输出错误:

 communication.cpp: In member function 'void Receiver::start(int)':
| communication.cpp:24:47: error: no matching function for call to 'std::thread::thread(<unresolved
 overloaded function type>, int&)'
| communication.cpp:24:47: note: candidates are:
| /home/toor/bluegiga-sdk/build/tmp/sysroots/apx4devkit/usr/include/c++/thread:133:7: note: std::th
read::thread(_Callable&&, _Args&& ...) [with _Callable = void (Receiver::*)(int), _Args = {int&}]
| /home/toor/bluegiga-sdk/build/tmp/sysroots/apx4devkit/usr/include/c++/thread:133:7: note:   no kn
own conversion for argument 1 from '<unresolved overloaded function type>' to 'void (Receiver::*&&)
(int)'

GCC 编译器是我正在构建的 SDK 提供的 ARM 编译器。到目前为止,它支持我尝试过的大多数其他 C++11 功能,所以我认为这不是问题所在,但我不确定。

最佳答案

我猜测 Receiver::thread_func 是一个非静态成员函数,在这种情况下您需要传递隐式第一个参数。假设你想让线程在同一个实例中运行,你需要传递this。否则,您需要将指针传递给另一个 Receiver 实例:

threads.push_back(std::thread(&Receiver::thread_func, this));

关于C++ 简单线程启动问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20051935/

相关文章:

c++ - Visual Studio Designer 在 VS2012 中不能用于 C++/CLI 文件,而在 VS2005 中可以。知道为什么?

c++ - 不使用 EOF 位作为我们的流提取条件的真正原因是什么?

c++ - vs 2008 部署项目不工作

c++ - 在 recvfrom 系统调用期间取消 C++11 std::thread?

c - 重新运行已取消的 pthread

c++ - 在重载的全局新运算符中使用静态对象导致核心转储运行时错误

c# - 为什么 float 在声明时显示精确表示

c - pthreads : allowed number of threads

有人可以解释一下吗?它处理 C 中的 malloc 和全局数组

C : pthread dataspecific destructor called only once