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

Why can't I compile this simple thread test?

本文关键字:线程 测试 简单 不能 编译 为什么      更新时间:2023-10-16

我想在我的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");

我想我的机器是问题所在,但为什么呢?

不知何故,您将代码构建为 C++03,可能是因为没有显式提供标准修订标志。 libc++,标准库的LLVM实现允许在C++03代码中使用<thread>。源具有以下类型的条件编译:

#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 标准修订标志重现您的错误。该错误甚至提到了这个候选人:

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)