C ++简单线程启动问题

时间:2013-11-18 15:50:10

标签: 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功能,所以我不认为这是问题,但我不确定。

1 个答案:

答案 0 :(得分:1)

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

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