【问题标题】:Threads in c++, cannot use parametersc++中的线程,不能使用参数
【发布时间】:2019-03-24 21:54:25
【问题描述】:

我正在尝试启动一个线程:

#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

在使用线程编译时,您需要做些什么不同的事情吗?我是否遗漏了一些非常明显的东西?

【问题讨论】:

  • #import - 这不是 c++,请编辑您的问题以包含 minimal reproducible example
  • 是的,抱歉的意思是#include
  • 使用-std=c++11编译开关
  • 添加 -std=c++11 有效!谢谢@M.M,我不知道这可能会出错......
  • 好的,我投票决定重新开放,一旦开放,就会有人将其发布为答案

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


【解决方案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 在 cmets 中提供上述答案。

【讨论】:

    猜你喜欢
    • 2011-03-30
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    相关资源
    最近更新 更多