在Linux中,C++多线程编程主要依赖于C++11标准库中的<thread>头文件。以下是一个简单的C++多线程实践示例:
首先,确保你的编译器支持C++11或更高版本。在编译时,使用-std=c++11或-std=c++14或-std=c++17等选项启用C++11特性。
创建一个名为multithreading_example.cpp的文件,并添加以下代码:
#include <iostream> #include <thread> #include <vector> // 线程函数 void print_hello(int id) { std::cout << "Hello from thread " << id << std::endl; } int main() { // 创建一个线程向量 std::vector<std::thread> threads; // 启动多个线程 for (int i = 0; i < 5; ++i) { threads.push_back(std::thread(print_hello, i)); } // 等待所有线程完成 for (auto& t : threads) { t.join(); } std::cout << "All threads finished." << std::endl; return 0; } g++ -std=c++11 multithreading_example.cpp -o multithreading_example ./multithreading_example 这个示例中,我们创建了一个名为print_hello的线程函数,它接受一个整数参数id,并打印一条消息。在main函数中,我们创建了一个std::vector来存储线程对象,并使用循环启动了5个线程。每个线程都调用print_hello函数,并传递一个唯一的ID。最后,我们使用join()方法等待所有线程完成。
注意:在实际应用中,多线程编程可能会涉及到更复杂的同步和互斥机制,例如使用std::mutex、std::lock_guard等来保护共享数据。这有助于避免数据竞争和其他潜在问题。