如何使用线程类编译 cpp 文件?

How do I compile a cpp file with the thread class?

本文关键字:cpp 文件 编译 何使用 线程      更新时间:2023-10-16

我正在学习使用线程,所以我正在尝试使用线程类运行代码,以便我可以同时运行函数。但是,尝试在终端中编译它,它说线程及其对象 t1 未声明。

threading.cpp:16:5: error: 'thread' was not declared in this scope
thread t1(task1, "Hello");
^~~~~~
threading.cpp:21:5: error: 't1' was not declared in this scope
t1.join();

我认为 g++ 不支持它,但我也在其参数中包含支持 c++11

g++ -std=c++11 threading.cpp

知道我应该对这个错误做什么吗?

(操作系统:视窗,gcc 版本 6.3.0(

下面提供了代码(来自网站的示例(:

#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();
}

知道我应该如何处理此错误吗?

您的代码在最新版本的 GCC (coliru.com( 中编译并运行良好。旧版本(例如 GCC 6(和-std=c++11.您的问题一定在其他地方:

  • 也许您正在使用一个非常旧的编译器?
  • 也许您的C++标准库标头未安装?
  • 也许您的C++标准库标题位于意想不到的地方?如果您使用的是自定义安装版本的编译器或标准库,则可能会发生这种情况。