在Ubuntu中进行C++多线程编程,你可以使用C++11引入的<thread>库。以下是一个简单的示例,展示了如何创建和使用线程:
-std=c++11或-std=c++14或-std=c++17等选项启用C++11支持。例如:g++ -std=c++11 -pthread your_file.cpp -o your_program
这里,-pthread选项用于启用POSIX线程支持。
<thread>头文件,并使用std::thread类创建线程。例如:#include <iostream>
#include <thread>
// 定义一个简单的函数,用于在线程中运行
void hello() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
// 创建一个线程,运行hello函数
std::thread t(hello);
// 等待线程完成
t.join();
std::cout << "Hello from main!" << std::endl;
return 0;
}
g++ -std=c++11 -pthread your_file.cpp -o your_program
./your_program
这将输出以下内容:
Hello from thread!
Hello from main!
这只是一个简单的示例,你可以根据需要创建多个线程,将它们传递给函数,甚至将线程作为参数传递给其他线程。<thread>库还提供了许多其他功能,如线程同步(例如std::mutex,std::lock_guard等)和线程局部存储(std::thread_local)。