无法使用参数调用线程函数
Calling threaded functions with arguments not possible
我知道这个问题看起来与已经回答的问题相似,但由于给他们的答案对我不起作用,我不认为这个问题是他们的翻版
我很清楚这个问题:我如何将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
标志或更高版本进行编译。
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在另一个线程中调用luaL_error会引发qWarning
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- 如何从线程中的不同模块调用函数?
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- 如何声明由多个线程调用的 C++ DLL 的内部类,而无需导出类
- 是否可以创建一个从不同类调用函数的线程?
- 为什么即使调用了析构函数,C++11 中的分离线程也可以执行
- 非静态成员失败的线程调用函数
- 线程调用的函数对对象删除是否安全?
- 将类成员函数作为线程调用到另一个类成员函数时发出警告消息
- 通过 Qt 中的线程调用 Rust 库
- Qt信号和插槽如果从QRunnable或其他线程调用,则不起作用
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 由并发无序映射查找线程调用的函数是否安全?
- 每个线程 C++ 保护以防止重入函数调用
- localtime() 函数正在调用 ___lll_lock_wait_private(),这会使线程陷入死锁
- 当我在C++中调用 struce 的只读静态成员时,线程是否安全
- 线程 std::调用未知类型,无法专门化函数错误
- 工作线程一直在等待,condition_variable甚至调用了notify_all