以下是OSTEP book中给出的有关使用测试和设置指令实现锁的代码。我的问题是,在这种实现中,未持有锁的线程难道不能调用解锁功能并拿走锁吗?
typedef struct __lock_t {
int flag;
} lock_t;
void init(lock_t *lock) {
// 0 indicates that lock is available, 1 that it is held
lock->flag = 0;
}
void lock(lock_t *lock) {
while (TestAndSet(&lock->flag, 1) == 1)
; // spin-wait (do nothing)
}
void unlock(lock_t *lock) {
lock->flag = 0;
}