鎖在編程中經(jīng)常被用到寒瓦。常用的鎖主要有兩種
- 樂(lè)觀鎖
- 悲觀鎖
樂(lè)觀鎖主要是基于版本號(hào)的實(shí)現(xiàn)孵构。給數(shù)據(jù)加一個(gè)version字段基本可以實(shí)現(xiàn)
本文主要實(shí)現(xiàn)一個(gè)悲觀鎖
主要思路:
- 維護(hù)一個(gè)內(nèi)部的鎖池
- 當(dāng)一個(gè)鎖被占用時(shí),其他地方獲取鎖將會(huì)失敗
下面給出了JS版本的實(shí)現(xiàn)
const LockUtils = {
lockPool: new Map(),//所有的鎖
acquire: function(lockName, timeout = 100){//傳入key名稱, 超時(shí)時(shí)間
const that = this;
end = new Date().getTime() + timeout;
while(new Date().getTime() <= end){
if(!that.lockPool.has(lockName)){
that.lockPool.set(lockName, {
name: lockName,
meta: '上下文信息'
})
return {
release: function(){//釋放鎖
that.lockPool.delete(lockName);
}
}
}
}
return undefined;
}
}
用例
const lock = LockUtils.acquire('lock');//獲取鎖
const lock2 = LockUtils.acquire('lock');//鎖被占用颈墅,獲取失敗
lock.release();//釋放鎖