为什么我不能编译这个简单的线程测试?

时间:2019-06-15 18:41:42

标签: c++ multithreading macos

我想在Macbook pro上使用线程测试某些东西,但无法正常工作。

Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

这是我计算机上安装的clang版本。我尝试编写一些线程向量,但是没有用,所以我回过头来复制了SO的示例。

#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");

    // Do other things...

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}

但是我遇到了编译器错误。

error: no matching constructor for initialization of
      'std::__1::thread'
    thread t1(task1, "Hello");

我猜我的机器出了问题,但是为什么呢?

1 个答案:

答案 0 :(得分:5)

以某种方式,您可能是通过未显式提供标准修订标志而将代码构建为C ++ 03。 libc ++是标准库的LLVM实现,允许在C ++ 03代码中使用<thread>。源具有following sort的条件编译:

#ifndef _LIBCPP_CXX03_LANG
    template <class _Fp, class ..._Args,
              class = typename enable_if
              <
                   !is_same<typename __uncvref<_Fp>::type, thread>::value
              >::type
             >
        _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
        explicit thread(_Fp&& __f, _Args&&... __args);
#else  // _LIBCPP_CXX03_LANG
    template <class _Fp>
    _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
    explicit thread(_Fp __f);
#endif

在C ++ 11和更高版本中,构造函数遵循C ++ 11标准。否则,它仅接受可调用对象,而没有其他参数。通过提供C ++ 03标准修订标记,我设法reproduce your error。错误甚至提到了该候选人:

prog.cc:16:12: error: no matching constructor for initialization of 'std::__1::thread'
    thread t1(task1, "Hello");
           ^  ~~~~~~~~~~~~~~
/opt/wandbox/clang-8.0.0/include/c++/v1/thread:408:9: note: candidate constructor template not viable: requires single argument '__f', but 2 arguments were provided
thread::thread(_Fp __f)