多线程c ++将参数传递给函数

时间:2016-06-06 08:39:29

标签: c++ multithreading

我一直试图将参数传递给线程函数,但一直无法。我试过阅读它(Passing multiple arguments to a threaded function),但我仍然无法弄明白。这是我的代码:

#include <iostream>
#include <thread>

using namespace std;

void func(int t)
{
    cout << t << endl;
}

int main()
{
    thread t1(func,4);
    t1.join();
    return 0;
}

我在命令行中运行它(我使用重要的zsh incase):

g++ test.cpp
./a.out

但我收到了这些错误:

thread_test.cpp:14:12: error: no matching constructor for initialization of 'std::__1::thread'
thread t1(func,4);
       ^  ~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:379: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:268: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:275:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
thread() _NOEXCEPT : __t_(0) {}
^
1 error generated.

如果这很重要,我正在使用带有OSX 10.11.4的mac

另外,要查看我正在编译的c ++的哪个版本,我运行了这个命令并将其输出:

g++ --version

配置: - prefix = / Applications / Xcode.app / Contents / Developer / usr --with-gxx-include-dir = / Applications / Xcode.app / Contents / Developer / Platforms / MacOSX.platform / Developer /SDKs/MacOSX10.11.sdk/usr/include/c++/4.2.1 Apple LLVM版本7.3.0(clang-703.0.31) 目标:x86_64-apple-darwin15.4.0 线程模型:posix InstalledDir:/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

1 个答案:

答案 0 :(得分:1)

通过-std=c++11,它会起作用;看下面的成绩单。 (在OS X上运行。)

nathanst% g++ t.cpp 
t.cpp:13:12: error: no matching constructor for initialization of 'std::__1::thread'
    thread t1(func,4);
           ^  ~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:379: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:268: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:275:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
    thread() _NOEXCEPT : __t_(0) {}
    ^
1 error generated.
nathanst% g++ -std=c++11 t.cpp