在Linux环境下使用C++实现并发控制,可以采用多种方法。以下是一些常用的并发控制机制和相应的示例代码:
互斥锁用于保护共享资源,确保同一时间只有一个线程可以访问。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 全局互斥锁
int shared_data = 0;
void increment() {
mtx.lock(); // 加锁
++shared_data;
mtx.unlock(); // 解锁
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Shared data: " << shared_data << std::endl;
return 0;
}
递归互斥锁允许同一个线程多次锁定同一个互斥锁,避免死锁。
#include <iostream>
#include <thread>
#include <mutex>
std::recursive_mutex mtx; // 全局递归互斥锁
int shared_data = 0;
void increment(int count) {
if (count <= 0) return;
mtx.lock(); // 加锁
++shared_data;
std::cout << "Thread " << std::this_thread::get_id() << " incremented shared_data to " << shared_data << std::endl;
mtx.unlock(); // 解锁
increment(count - 1);
}
int main() {
std::thread t1(increment, 5);
std::thread t2(increment, 3);
t1.join();
t2.join();
std::cout << "Final shared data: " << shared_data << std::endl;
return 0;
}
条件变量用于线程间的同步,允许一个线程等待某个条件成立,而另一个线程在条件成立时通知等待的线程。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void worker() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return ready; }); // 等待条件成立
std::cout << "Worker thread is processing data..." << std::endl;
}
void trigger() {
std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟一些工作
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one(); // 通知等待的线程
}
int main() {
std::thread t1(worker);
std::thread t2(worker);
trigger();
t1.join();
t2.join();
return 0;
}
原子操作可以在不使用锁的情况下实现线程安全的操作。
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> shared_data(0);
void increment() {
++shared_data; // 原子操作
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Shared data: " << shared_data << std::endl;
return 0;
}
读写锁允许多个线程同时读取共享资源,但只允许一个线程写入共享资源。
#include <iostream>
#include <thread>
#include <shared_mutex>
std::shared_mutex rw_mtx; // 全局读写锁
int shared_data = 0;
void reader() {
std::shared_lock<std::shared_mutex> lock(rw_mtx); // 读锁
std::cout << "Reader thread read shared_data: " << shared_data << std::endl;
}
void writer() {
std::unique_lock<std::shared_mutex> lock(rw_mtx); // 写锁
++shared_data;
std::cout << "Writer thread wrote shared_data: " << shared_data << std::endl;
}
int main() {
std::thread t1(reader);
std::thread t2(writer);
std::thread t3(reader);
t1.join();
t2.join();
t3.join();
return 0;
}
这些示例展示了在Linux环境下使用C++实现并发控制的几种常见方法。根据具体的需求和场景,可以选择合适的并发控制机制。