Operating system 两个可以';t保持计数器值的一致性
这是TAS代码Operating system 两个可以';t保持计数器值的一致性,operating-system,Operating System,这是TAS代码 boolean TAS(*target) { boolean rv = *target; //Save the initial value *target = true; //Set lock return rv; //Return initial value } 以下代码表示使用TA在线程安全计数器上执行增量操作的两次不同尝试,以保持计数器值的一致性 代码1 Counter::Increment() {
boolean TAS(*target)
{
boolean rv = *target; //Save the initial value
*target = true; //Set lock
return rv; //Return initial value
}
以下代码表示使用TA在线程安全计数器上执行增量操作的两次不同尝试,以保持计数器值的一致性
代码1
Counter::Increment() {
while (TAS(&lock)) ;
value++;
lock = FREE;
memory_barrier();
}
代码2
Counter::Increment() {
while (lock == BUSY && TAS(&lock)) ;
value++;
lock = FREE;
memory_barrier();
}
假设
空闲==false
和忙碌==true
,则无法处理一致性的每个代码将出现什么问题,以下是一个打破互斥的流程:
Start thread 1:
Increment
TAS
rv = *lock; // FREE
Switch to thread 2:
Increment
TAS
rv = *lock; // FREE
*lock = BUSY;
return rv; // FREE
Load value 0 from memory and push it into the stack
Switch to thread 1:
*lock = BUSY;
return rv; // FREE
Load value 0 from memory and push it into the stack
Push 1 into the stack
Pop two integers from the stack and add them
Store the result (0 + 1) into value
Switch to thread 2:
Push 1 into the stack
Pop two integers from the stack and add them
Store the result (0 + 1) into value