文章目录
无锁队列
本文讲述了无锁队列的原理、分类、底层数据结构、应用场景,以及两种实现方式。
1. 无锁队列原理
1.1 多线程并发控制策略介绍
-
blocking(阻塞)
阻塞是指在多线程操作共享资源时,通过锁等同步原语来协调访问。当一个线程试图访问已被其他线程持有的资源时,它会等待直到该资源被释放。
特点:通过锁等机制阻塞线程实现同步;系统内可能出现循环等待的情况,造成死锁,导致整个系统无法向前推进。
以互斥锁举例:
#include <iostream> #include <mutex> #include <thread> #include <vector> std::mutex mtx; // 全局互斥锁 int shared_resource = 0; void blockingIncrement() { std::lock_guard<std::mutex> lock(mtx); // 获取锁,阻塞其他线程 ++shared_resource; std::cout << "Blocking increment: " << shared_resource << "\n"; } int main() { std::vector<std::thread> threads; for (int i = 0; i < 10; ++i) { threads.emplace_back(blockingIncrement); } for (auto& t : threads) { t.join(); } return 0; }
-
lock free(无锁)
无锁是一种非阻塞的并发控制方式,确保在操作过程中,至少有一个线程能够在有限的重试后完成任务。无锁操作通常依赖于原子操作,如CAS(Compare-And-Swap),在不需要显式锁的情况下保证数据的正确性。
**特点:**通常依赖CAS等原子操作访问共享数据;非阻塞、无死锁,保证系统内至少有一个线程能够向前推进并在有限时间内完成;但可能出饥饿和饿死。
举例:
#include <iostream> #include <atomic> #include <thread> #include <vector> std::atomic<int> atomic_resource{ 0}; void lockFreeIncrement() { int old_value = atomic_resource.load(); while (!atomic_resource.compare_exchange_weak(old_value, old_value + 1)) { // CAS失败时,old_value会被重新加载当前值,继续尝试 } std::cout << "Lock-Free increment: " << atomic_resource.load() << "\n"; } int main() { std::vector<std::thread> threads; for (int i = 0; i < 10; ++i) { threads.emplace_back(lockFreeIncrement); } for (auto& t : threads) { t.join(); } return 0; }
-
wait free(无等待)
无等待是更严格的一种无锁设计,保证所有线程都能在有限步数内完成操作。无等待算法要求即使在最坏情况下,每个线程都能在有限的时间内获得进展,而无需重试或等待其他线程。
特点:即使在最坏的情况下,系统内每个线程都能够在有限的时间内取得进展,不会有饿死现象出现。
举例:
#include <iostream> #include <atomic> #include <thread> #include <vector> std::atomic<int> waitFreeResource{ 0}; void waitFreeIncrement() { int newValue = waitFreeResource.fetch_add(1) + 1; // 无等待操作 std::cout << "Wait-Free increment: " << newValue << "\n"; } int main() { std::vector<std::thread> threads; for (int i = 0; i < 10; ++i) { threads.emplace_back(waitFreeIncrement); } for (auto& t : threads) { t.join(); } return 0; }
1.2 无锁队列概念
**无锁队列(Lock-Free Queue)**是一种在多线程环境下用于存储和访问数据的队列数据结构,避免了传统锁(如互斥锁、信号量)带来的线程阻塞问题。无锁队列通过利用原子操作(如CAS,Compare-And-Swap)来保证队列操作的安全性,使得在高并发环境中拥有更好的性能和较低的资源开销。
无锁队列的主要目标是实现”非阻塞“的数据操作。允许多个线程并发地执行入队和出队操作,不会因为等待锁释放而阻塞。
无锁队列依赖CAS原子操作来保证只有一个线程成功地更新队列队列状态,而失败的线程会重新操作,指导成功。
特点:
- 依靠原子操作CAS来保证线程安全
- 非阻塞,线程不会因为原子操作失败而陷入阻塞
- 无死锁,保证系统内至少有一个线程能够运行并完成原子操作
无锁队列的优点: