在Linux环境下使用C++实现并发控制,可以采用多种方法。以下是一些常用的并发控制机制:
互斥锁(Mutexes): 互斥锁是最基本的同步机制,用于确保多个线程不会同时访问共享资源。
#include <mutex>
#include <thread>
std::mutex mtx; // 全局互斥锁
void print_block(int n, char c) {
mtx.lock(); // 加锁
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
mtx.unlock(); // 解锁
}
int main() {
std::thread th1(print_block, 50, '*');
std::thread th2(print_block, 50, '$');
th1.join();
th2.join();
return 0;
}
递归互斥锁(Recursive Mutexes): 如果一个线程需要多次获取同一个互斥锁,可以使用递归互斥锁。
#include <mutex>
#include <thread>
std::recursive_mutex rmtx;
void func(int n) {
if (n <= 0) return;
rmtx.lock();
func(n - 1);
rmtx.unlock();
}
int main() {
std::thread t(func, 10);
t.join();
return 0;
}
条件变量(Condition Variables): 条件变量允许线程等待某个条件成立,或者通知其他线程某个条件已经成立。
#include <condition_variable>
#include <mutex>
#include <thread>
#include <queue>
std::mutex mtx;
std::condition_variable cv;
std::queue<int> q;
void producer() {
for (int i = 0; i < 10; ++i) {
std::unique_lock<std::mutex> lock(mtx);
q.push(i);
cv.notify_one(); // 通知消费者
}
}
void consumer() {
while (true) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] { return !q.empty(); }); // 等待直到队列非空
int val = q.front();
q.pop();
if (val == 9) break; // 如果收到最后一个值,退出循环
}
}
int main() {
std::thread prod(producer);
std::thread cons(consumer);
prod.join();
cons.join();
return 0;
}
读写锁(Read-Write Locks): 当共享资源读取操作远多于写入操作时,使用读写锁可以提高性能。
#include <shared_mutex>
#include <thread>
std::shared_mutex rw_mtx;
void read_func() {
std::shared_lock<std::shared_mutex> lock(rw_mtx); // 共享锁
// 执行读操作
}
void write_func() {
std::unique_lock<std::shared_mutex> lock(rw_mtx); // 排他锁
// 执行写操作
}
int main() {
// 创建多个读取线程和写入线程
return 0;
}
原子操作(Atomic Operations): 对于简单的数据类型,可以使用原子操作来避免锁的开销。
#include <atomic>
#include <thread>
std::atomic<int> counter(0);
void increment_counter() {
for (int i = 0; i < 1000; ++i) {
counter.fetch_add(1, std::memory_order_relaxed);
}
}
int main() {
std::thread t1(increment_counter);
std::thread t2(increment_counter);
t1.join();
t2.join();
std::cout << "Counter: " << counter.load() << '\n';
return 0;
}
信号量(Semaphores): 信号量是一种更高级的同步机制,可以用来控制对共享资源的访问。
#include <semaphore>
#include <thread>
std::binary_semaphore sem(1); // 二进制信号量
void critical_section() {
sem.acquire(); // 获取资源
// 执行关键区代码
sem.release(); // 释放资源
}
int main() {
std::thread t1(critical_section);
std::thread t2(critical_section);
t1.join();
t2.join();
return 0;
}
在使用这些并发控制机制时,需要注意避免死锁和其他同步问题。合理地设计程序结构和锁的使用策略对于编写高效且安全的并发程序至关重要。