在Linux环境下使用C++实现多线程并发,主要依赖于C++11标准库中的<thread>头文件。以下是一个简单的示例,展示了如何创建和使用多个线程:
#include <iostream>
#include <thread>
#include <vector>
// 线程函数
void threadFunction(int id) {
std::cout << "Thread " << id << " is running." << std::endl;
}
int main() {
const int numThreads = 5;
std::vector<std::thread> threads;
// 创建线程
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back(threadFunction, i);
}
// 等待所有线程完成
for (auto& t : threads) {
t.join();
}
std::cout << "All threads have finished." << std::endl;
return 0;
}
包含头文件:
#include <iostream>
#include <thread>
#include <vector>
<iostream>:用于输入输出操作。<thread>:提供线程相关的功能。<vector>:用于存储线程对象。线程函数:
void threadFunction(int id) {
std::cout << "Thread " << id << " is running." << std::endl;
}
创建线程:
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back(threadFunction, i);
}
std::thread创建线程,并将线程函数和参数传递给它。emplace_back直接在vector中构造std::thread对象。等待线程完成:
for (auto& t : threads) {
t.join();
}
join()方法会阻塞调用线程,直到对应的线程完成执行。线程安全:在多线程环境中,对共享资源的访问需要进行同步,以避免数据竞争。可以使用互斥锁(std::mutex)、条件变量(std::condition_variable)等同步机制。
异常处理:在线程函数中抛出的异常需要妥善处理,否则可能导致程序崩溃。
资源管理:确保在所有线程完成后释放资源,避免内存泄漏。
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
std::mutex mtx; // 全局互斥锁
void threadFunction(int id) {
std::lock_guard<std::mutex> lock(mtx); // 自动管理锁
std::cout << "Thread " << id << " is running." << std::endl;
}
int main() {
const int numThreads = 5;
std::vector<std::thread> threads;
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back(threadFunction, i);
}
for (auto& t : threads) {
t.join();
}
std::cout << "All threads have finished." << std::endl;
return 0;
}
在这个示例中,std::lock_guard用于自动管理互斥锁的生命周期,确保在离开作用域时自动释放锁。
通过这些基本步骤和注意事项,你可以在Linux环境下使用C++实现多线程并发。