一、互斥锁的实现1
class mutex
{
public:
void lock()
{
while (locked); // 关键行1
locked = 1; // 关键行2
}
void unlock()
{
locked = 0;
}
private:
int locked = 0;
};
二、自旋锁的实现
class lock_t
{
private:
int flag;
public:
lock_t()
{
flag = 0;
}
void lock()
{
while (TestAndSet(flag, 1) == 1);
// 不停地自旋,TestAndSet就是将1和flag的值原子的交换,硬件指令
}
void unlock() { flag = 0; }
};
$TestAndSet()$是怎么实现的?