在Ubuntu上进行C++多线程编程,你需要使用C++11标准库中的<thread>
头文件。以下是一个简单的示例,展示了如何在Ubuntu上使用C++11多线程:
-std=c++11
标志启用C++11支持。例如,如果你有一个名为main.cpp
的源文件,可以使用以下命令编译:g++ -std=c++11 main.cpp -o main
main.cpp
的文件,并添加以下代码:#include <iostream>
#include <thread>
// 定义一个简单的函数,用于在线程中运行
void hello_thread() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
// 创建一个线程对象,并将hello_thread函数作为参数传递给它
std::thread t(hello_thread);
// 等待线程完成
t.join();
std::cout << "Hello from the main thread!" << std::endl;
return 0;
}
g++ -std=c++11 main.cpp -o main
./main
这将输出以下内容:
Hello from a thread!
Hello from the main thread!
这只是一个简单的示例,C++11标准库还提供了许多其他功能,如互斥锁、条件变量、原子操作等,以帮助你更好地控制多线程编程。你可以查阅C++11标准库文档以获取更多信息。