由于在多处理器环境中某些资源的有限性,有时需要互斥访问(mutual exclusion),这时候就需要引入锁的概念,只有获取了锁的线程才能够对资源进行访问,由于多线程的核心是CPU的时间分片,所以同一时刻只能有一个线程获取到锁。那么就面临一个问题,那么没有获取到锁的线程应该怎么办?
通常有两种处理方式:一种是没有获取到锁的线程就一直循环等待判断该资源是否已经释放锁,这种锁叫做自旋锁,它不用将线程阻塞起来(NON-BLOCKING);还有一种处理方式就是把自己阻塞起来,等待重新调度请求,这种叫做互斥锁。
自旋锁的原理比较简单,如果持有锁的线程能在短时间内释放锁资源,那么那些等待竞争锁的线程就不需要做内核态和用户态之间的切换进入阻塞状态,它们只需要等一等(自旋),等到持有锁的线程释放锁之后即可获取,这样就避免了用户进程和内核切换的消耗。由于获取锁的线程一直处于活跃状态,但是并没有执行任何有效的任务,因此使用这种锁会造成busy-waiting,也就是CPU不断的进行检测操作,而无法处理其他任务。
在这里使用atomic_flag实现自旋锁
atomic_flag:c++11 头文件中最简单的原子类型: 。atomic_flag 一种简单的原子布尔类型,只支持两种操作,test-and-set 和 clear。
atomic_flag 需要被ATOMIC_FLAG_INIT初始化,初始化后即为false,
调用test_and_set()时,如果标记是false,将其设置为true, 然后该函数返回false;如果标记为true, 不进行设置(因为已经为true了), 返回true。
下面看代码实现:
#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
#include<mutex>
class spin_lock
{
public:
spin_lock() = default;
spin_lock(const spin_lock& obj) = delete;
spin_lock& operator=(const spin_lock& obj) = delete;
spin_lock(const spin_lock&& obj) = delete;
spin_lock& operator=(const spin_lock&& obj) = delete;
void lock()
{
while (m_flag.test_and_set(std::memory_order_acquire)){}
}
void unlock()
{
m_flag.clear(std::memory_order_release);
}
private:
std::atomic_flag m_flag = ATOMIC_FLAG_INIT;
};
spin_lock g_mutex;
void f(int n)
{
for (int cnt = 0; cnt < 10; ++cnt)
{
//方式一
std::lock_guard<spin_lock> lc(g_mutex);
printf("Output from thread %d\n", n);
}
/*
方式二
for (int cnt = 0; cnt < 10; ++cnt)
{
g_mutex.lock();
printf("Output from thread %d\n", n);
g_mutex.unlock();
}*/
}
int main()
{
std::vector<std::thread> v;
for (int n = 0; n < 10; ++n)
{
v.emplace_back(f, n);
}
for (auto& t : v)
{
t.join();
}
system("pause");
}
结果: