多线程的那点儿事(之顺序锁)
【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】
在互斥数据访问中有一种多读少写的情况。正对这么一种情形,我们也提出了读写锁的方案。但是呢,这个锁有些缺陷。什么缺陷呢?那就是,这个写锁需要在所有的读锁完成之后才能写。否则的话,写锁需要这么一直等下去。
那么,有没有什么办法能使得写操作快速一点进行呢?那就是顺序锁。
copy to clipboardprint?typedef struct _SEQUENCE_LOCK
{
unsigned int sequence;
HANDLE hLock;
}SEQUENCE_LOCK;
typedef struct _SEQUENCE_LOCK
{
unsigned int sequence;
HANDLE hLock;
}SEQUENCE_LOCK; 有了这么一个数据结构之后。那么读锁怎么开始呢,
copy to clipboardprint?unsigned int get_lock_begin(SEQUENCE_LOCK* hSeqLock)
{
assert(NULL != hSeqLock);
return hSeqLock->sequence;
}
int get_lock_retry(SEQUENCE_LOCK* hSeqLock, unsigned int value)
{
unsigned int new_value;
assert(NULL != hSeqLock);
new_value = hSeqLock->sequence;
return (new_value & 0x1) || (new_value ^ value);
}
unsigned int get_lock_begin(SEQUENCE_LOCK* hSeqLock)
{
assert(NULL != hSeqLock);
return hSeqLock->sequence;
}
int get_lock_retry(SEQUENCE_LOCK* hSeqLock, unsigned int value)
{
unsigned int new_value;
assert(NULL != hSeqLock);
new_value = hSeqLock->sequence;
return (new_value & 0x1) || (new_value ^ value);
} 自然写锁也需要修改了,
copy to clipboardprint?void get_write_lock(SEQUENCE_LOCK* hSeqLock)
{
assert(NULL != hSeqLock);
WaitForSingleObject(hSeqLock->hLock);
hSeqLock->sequence ++;
}
void release_write_lock(SEQUENCE_LOCK* hSeqLock)
{
assert(NULL != hSeqLock);
hSeqLock->sequence ++;
ReleaseMutex(hSeqLock->hLock);
}
void get_write_lock(SEQUENCE_LOCK* hSeqLock)
{
assert(NULL != hSeqLock);
WaitForSingleObject(hSeqLock->hLock);
hSeqLock->sequence ++;
}
void release_write_lock(SEQUENCE_LOCK* hSeqLock)
{
assert(NULL != hSeqLock);
hSeqLock->sequence ++;
ReleaseMutex(hSeqLock->hLock);
} 如果应用呢,其实也不难,
copy to clipboardprint?void read_process(SEQUENCE_LOCK* hSeqLock)
{
unsigned int sequence;
do{
sequence = get_lock_begin(hSeqLock);
/* read operation */
}while(get_lock_retry(hSeqLock, sequence));
}
void write_process(SEQUENCCE_LOCK* hSeqLock)
{
get_write_lock(hSeqLock);
/* write operation */
release_write_lock(hSeqLock);
}
void read_process(SEQUENCE_LOCK* hSeqLock)
{
unsigned int sequence;
do{
sequence = get_lock_begin(hSeqLock);
/* read operation */
}while(get_lock_retry(hSeqLock, sequence));
}
void write_process(SEQUENCCE_LOCK* hSeqLock)
{
get_write_lock(hSeqLock);
/* write operation */
release_write_lock(hSeqLock);
}
总结:
(1)读锁退出有两个条件,要么写操作正在进行呢,要么没有写锁
(2)写锁之间需要互斥操作
(3)互斥操作的数据不能是指针,否则有可能在访问的时候会造成异常,因为有可能边写边读
(4)顺序锁代替不了读写锁,因为读写锁可以保证所有的数据操作,而顺序锁不行
补充:软件开发 , 其他 ,