在线程内调用线程会给我错误,如果我只调用函数就可以正常工作

Calling a thread inside a thread gives me errors, works fine if I just call the function

你能从另一个线程中调用一个线程吗?我有一个 C++ 程序,它与一个与串口通信的 C 库交互。我可以调用该函数并进行编译,但是当我尝试使用线程调用它时,它会抛出一些错误。 我有使用 MATLAB 和 Arduino 的大学经验,并且用 C++ 一起破解了一些东西,但我对 C++ 还是很陌生。这是我第一次尝试使用线程。 我很乐意提供任何其他需要的信息。

编译得很好:

int main()
{
    unsigned char readVals[4096];
    CheckCOMPort(readVals); //This is the function call in question
    return 0;
}

但事实并非如此:

int main()
{
    unsigned char readVals[4096];
    std::thread scanCOMPort(CheckCOMPort(readVals)); //This is the thread function call in question
    stop_flag = true;
    scanCOMPort.join();

    return 0;
}

错误:

||=== Build: Debug in ComPortReadWrite (compiler: GNU GCC Compiler) ===|
C:\...\functional||In instantiation of 'struct std::_Bind_simple<bool()>':|
C:\...\thread|142|required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = bool; _Args = {}]'|
C:\...\COMPort.cpp|122|required from here|
C:\...\functional|1505|error: no type named 'type' in 'class std::result_of<bool()>'|
C:\...\functional|1526|error: no type named 'type' in 'class std::result_of<bool()>'|

您正在尝试在主线程中实际调用 CheckCOMPort(),然后将其 return 值传递给 std::thread。那不是你想要的。您需要将 CheckCOMPort() 本身传递给 std::thread,以及您希望线程在线程调用它时传递给 CheckCOMPort() 的参数。

试试这个:

int main()
{
    unsigned char readVals[4096];
    std::thread scanCOMPort(CheckCOMPort, readVals);
    stop_flag = true;
    scanCOMPort.join();

    return 0;
}

尝试给出函数指针,然后用逗号分隔它的参数。

std::thread scanCOMPort(CheckCOMPort, readVals);

您可以在 Internet 上阅读有关其工作原理的更多信息。