C ++中的线程无法使用参数

时间:2018-10-20 02:38:16

标签: c++ multithreading macos compiler-errors g++

我正在尝试启动线程t:

#include <iostream>
#include <fstream>
#include <string>
#include <thread>

void function(int p1, int p2, int p3){
  std::cout<<p1<<p2<<p3<<std::endl;
}

int main(int argc, char const *argv[]) {
  std::cout<<"starting"<<std::endl;
  std::thread t(function, 1, 2, 3);
  std::cout<<"created thread"<<std::endl;
  t.join();
  std::cout<<"end"<<std::endl;
  return 0;
}

我的编译器告诉我:

doesntwork.cpp:12:15: error: no matching constructor for
      initialization of 'std::thread'
  std::thread t(function, 1, 2, 3);
              ^ ~~~~~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/usr/include/c++/v1/thread:408:9: note: 
      candidate constructor template not viable: requires single
      argument '__f', but 4 arguments were provided
thread::thread(_Fp __f)
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/thread:289:5: note: 
      candidate constructor not viable: requires 1 argument, but 4
      were provided
    thread(const thread&);
    ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/thread:296:5: note: 
      candidate constructor not viable: requires 0 arguments, but
      4 were provided
    thread() _NOEXCEPT : __t_(_LIBCPP_NULL_THREAD) {}
    ^
1 error generated.

在第一种情况下,它告诉我对于线程t,没有构造函数可以使用多个参数,而如果我仅删除参数(p1,p2,p3),则它也不起作用,因为我没有通过任何精液。...

编译器信息:

Configured with: --prefix=/Library/Developer/CommandLineTools/usr 

--with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 10.0.0 (clang-1000.10.44.2)
Target: x86_64-apple-darwin17.7.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

使用的内置命令:g++ doesntwork.cpp -o doesntwork.out

使用线程编译时,您需要做些其他的事情吗?我错过了一些非常明显的东西吗?

1 个答案:

答案 0 :(得分:1)

在macOS上,g ++(来自Xcode:10.0版(10A255))被别名为clang,默认情况下它不适用于c ++ 11线程。要解决此问题,您必须使用-std=c++11开关。

示例:

g++ -std=c++11 fileToCompile.cpp -o outputFile.out

这应该使您可以使用c ++ 11线程编译c ++代码。

感谢@ M.M在评论中提供上述答案。