Forpersonaluseonlyinstudyandresearch;mercialuse多线程的那点儿事(之顺序锁)在互斥数据访问中有一种多读少写的情况。正对这么一种情形,我们也提出了读写锁的方案。但是呢,这个锁有些缺陷。什么缺陷呢?那就是,这个写锁需要在所有的读锁完成之后才能写。否则的话,写锁需要这么一直等下去。那么,有没有什么办法能使得写操作快速一点进行呢?那就是顺序锁。[cpp]viewplaincopytypedefstruct_SEQUENCE_LOCK{unsignedintsequence;HANDLEhLock;}SEQUENCE_LOCK;有了这么一个数据结构之后。那么读锁怎么开始呢,[cpp]viewplaincopyunsignedintget_lock_begin(SEQUENCE_LOCK*hSeqLock){assert(NULL!=hSeqLock);returnhSeqLock->sequence;}intget_lock_retry(SEQUENCE_LOCK*hSeqLock,unsignedintvalue){unsignedintnew_value;assert(NULL!=hSeqLock);new_value=hSeqLock->sequence;return(new_value&0x1)||(new_value^value);}自然写锁也需要修改了,[cpp]viewplaincopyvoidget_write_lock(SEQUENCE_LOCK*hSeqLock){assert(NULL!=hSeqLock);WaitForSingleObject(hSeqLock->hLock);hSeqLock->sequence++;}voidrelease_write_lock(SEQUENCE_LOCK*hSeqLock){assert(NULL!=hSeqLock);hSeqLock->sequence++;ReleaseMutex(hSeqLock->hLock);}如果应用呢,其实也不难,[cpp]viewplaincopyvoidread_process(SEQUENCE_LOCK*hSeqLock){unsignedintsequence;do{sequence=get_lock_begin(hSeqLock);/*readoperation*/}while(get_lock_retry(hSeqLock,sequence));}voidwrite_process(E_LOCK*hSeqLock){get_write_lock(hSeqLock);/*writeoperation*/release_write_lock(h
多线程的那点儿事(之顺序锁) 来自淘豆网m.daumloan.com转载请标明出处.