自旋锁和互斥锁的选择 C++ 举例
时间: 2024-04-30 18:21:42 浏览: 13
自旋锁和互斥锁都是用来保护共享资源的锁机制,它们的选择取决于应用场景和需求。
自旋锁适用于锁的持有时间短,竞争激烈的情况下。它会在获取不到锁时不断地循环检查锁的状态,直到获取到锁为止。这样可以避免线程进入睡眠状态,从而提高锁的效率。
互斥锁适用于锁的持有时间长,竞争不激烈的情况下。它会在获取不到锁时将线程进入睡眠状态,直到获取到锁为止。这样可以避免线程占用过多的 CPU 资源。
下面是一个 C++ 的例子,演示了如何使用自旋锁和互斥锁:
```cpp
#include <iostream>
#include <thread>
#include <atomic>
#include <mutex>
// 自旋锁
class SpinLock {
public:
void lock() {
while (flag.test_and_set(std::memory_order_acquire));
}
void unlock() {
flag.clear(std::memory_order_release);
}
private:
std::atomic_flag flag = ATOMIC_FLAG_INIT;
};
// 互斥锁
std::mutex mtx;
// 共享资源
int cnt = 0;
// 使用自旋锁保护共享资源
void spinLockFunc() {
static SpinLock lock;
for (int i = 0; i < 1000000; ++i) {
lock.lock();
++cnt;
lock.unlock();
}
}
// 使用互斥锁保护共享资源
void mutexFunc() {
for (int i = 0; i < 1000000; ++i) {
std::unique_lock<std::mutex> lck(mtx);
++cnt;
}
}
int main() {
std::thread t1(spinLockFunc);
std::thread t2(spinLockFunc);
std::thread t3(mutexFunc);
std::thread t4(mutexFunc);
t1.join();
t2.join();
t3.join();
t4.join();
std::cout << cnt << std::endl;
return 0;
}
```
在这个例子中,我们创建了一个共享资源 `cnt`,并分别使用自旋锁和互斥锁来保护它。其中,`spinLockFunc` 和 `mutexFunc` 分别代表使用自旋锁和互斥锁的线程函数。
我们通过创建 4 个线程来模拟多线程并发访问共享资源的情况,最后输出 `cnt` 的值。