C++简单的线程启动问题

C++ Simple Thread Start Issue

本文关键字:启动 问题 线程 简单 C++      更新时间:2023-10-16

我有相当简单的代码,我找到的每个示例看起来都非常相似。 我确定我缺少一些基本的东西,所以任何帮助将不胜感激。

/*-------------------------------------
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));