有两个线程,一个负责读数据,另一个负责写数据
写线程:
data[10]//读写访问的数据区域
Empyt[10]//标记数据块
if(Empty[writeIndex]){
//写数据到data[writeindex]块中;
Empty[writeindex]=false;
writeindex=(writeindex+1)%10
}
读线程
if(!Empty[readIndex]){
//读data[readindex];
Empty[readindex]=true;
readindex=(eadindex+1)%10
}
能否实现同步
写线程:
data[10]//读写访问的数据区域
Empyt[10]//标记数据块
if(Empty[writeIndex]){
//写数据到data[writeindex]块中;
Empty[writeindex]=false;
writeindex=(writeindex+1)%10
}
读线程
if(!Empty[readIndex]){
//读data[readindex];
Empty[readindex]=true;
readindex=(eadindex+1)%10
}
能否实现同步
写指针初值 int writeIndex=0;
读指针初值 int readIndex=0;取数据个数
int GetDataCount()
{
return (writeIndex>=readIndex) ? writeIndex-readIndex ? writeIndex+10-readIndex;
}写线程:
while (GetDataCount()>=9) Sleep(10); // 数据没有取走,等待
写数据到data[writeindex]块中;
writeindex=(writeindex+1)%10读线程
while (GetDataCount()==0) Sleep(10); // 没有数据,等待
读data[readindex];
readindex=(readindex+1)%10;
15.2.1. Compare and Swap
The approach taken by most processor architectures, including IA32 and Sparc, is to implement a compare-and-swap (CAS) instruction. (Other processors, such as PowerPC, implement the same functionality with a pair of instructions: loadlinked and store-conditional.) CAS has three operandsa memory location V on which to operate, the expected old value A, and the newvalue B. CAS atomically updates V to the new value B, but only if the value in V matches the expected old value A; otherwise it does nothing. In either case, it returns the value currently in V. (The variant called compare-and-set instead returns whether the operation succeeded.) CAS means "I think V should have the value A; if it does, put B there, otherwise don't change it but tell me I was wrong." CAS is an optimistic techniqueit proceeds with the update in the hope of success, and can detect failure if another thread has updated the variable since it was last examined. SimulatedCAS in Listing 15.1 illustrates the semantics (but not the implementation or performance) of CAS.When multiple threads attempt to update the same variable simultaneously using CAS, one wins and updates the variable's value, and the rest lose. But the losers are not punished by suspension, as they could be if they failed to acquire a lock; instead, they are told that they didn't win the race this time but can try again. Because a thread that loses a CAS is not blocked, it can decide whether it wants to try again, take some other recovery action, or do nothing.[3] This flexibility eliminates many of the liveness hazards associated with locking (though in unusual cases can introduce the risk of livelocksee Section 10.3.3).[3] Doing nothing may be a perfectly sensible response to a failed CAS; in some nonblocking algorithms, such as the linked queue algorithm in Section 15.4.2, a failed CAS means that someone else already did the work you were planning to do.