无法使用参数调用线程函数

Calling threaded functions with arguments not possible

本文关键字:调用 线程 函数 参数      更新时间:2023-10-16

我知道这个问题看起来与已经回答的问题相似,但由于给他们的答案对我不起作用,我不认为这个问题是他们的翻版

我很清楚这个问题:我如何将c++函数作为一个有1个或多个参数的线程来调用,这个问题已经回答了好几次了——无论是在这里还是在各种教程中——在每种情况下,答案都很简单,这就是实现它的方法:

(示例直接取自此问题)

#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}

然而,我已经尝试过复制粘贴这段代码和更多(或多或少相同)如何做到这一点的例子,然而,每次我编译(通过像g++ test.cpp -o test.app这样的termial(必须添加.app,因为我在Mac上(注意,这种编译方式实际上对我有效,而且错误根本不是我不知道如何编译c++程序的结果))这样的程序时,我都会收到以下错误消息:

test.cpp:16:12: error: no matching constructor for initialization of 'std::__1::thread'
thread t1(task1, "Hello");
^  ~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:389:9: note: candidate constructor template not viable: requires single argument '__f', but
2 arguments were provided
thread::thread(_Fp __f)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:297:5: note: candidate constructor not viable: requires 1 argument, but 2 were provided
thread(const thread&);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:304:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
thread() _NOEXCEPT : __t_(0) {}

因此,我的问题是,与所有可能生成带自变量的线程函数的人相比,我做错了什么?由于我没有发现遇到类似问题的人提出任何问题,我不认为这个问题是许多我如何调用带自变量的螺纹函数的重复

据我所知,使用线程不需要任何特定的编译器标志,而且由于我完全可以在没有参数的情况下运行带有线程函数的程序,所以你不能声称我的计算机或编译器不可能完全使用线程。

根据gcc的版本,您应该添加编译器开关-std=c++11或-std=c++0x。

我可以在这里编译

用C++14,得到如下输出。

task1 says: Hello

使用-std=c++11标志或更高版本进行编译。