在Ubuntu中编写C++多线程程序,你需要使用C++11标准库中的<thread>
头文件。下面是一个简单的示例,展示了如何创建和使用多个线程。
首先,确保你的编译器支持C++11或更高版本。在编译时,你需要添加-std=c++11
(或更高版本,如-std=c++14
、-std=c++17
等)标志。
这是一个简单的C++多线程示例:
#include <iostream>
#include <thread>
// 线程函数
void print_hello() {
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
int main() {
// 创建两个线程
std::thread t1(print_hello);
std::thread t2(print_hello);
// 等待线程完成
t1.join();
t2.join();
std::cout << "Hello from main thread " << std::this_thread::get_id() << std::endl;
return 0;
}
将此代码保存到名为multithread_example.cpp
的文件中,然后使用以下命令编译:
g++ -std=c++11 multithread_example.cpp -o multithread_example
运行生成的可执行文件:
./multithread_example
输出可能类似于以下内容:
Hello from thread 140735609822976
Hello from main thread 140735593408256
Hello from thread 140735576993664
注意线程的执行顺序可能会有所不同,因为它们是并发运行的。
这只是一个简单的示例,C++多线程编程还包括许多其他功能,如互斥锁、条件变量、原子操作等。你可以查阅C++标准库文档以了解更多关于多线程编程的信息。