- 論壇徽章:
- 0
|
PostgreSQL鎖機制
閆華 postgres_fan@yahoo.com.cn
4鎖機制
PostgreSQL內(nèi)部有三種類型的鎖,分別是自旋鎖(spin lock)、輕量級鎖(Lightweight lock)和常規(guī)鎖(regular lock)。自旋鎖和輕量級鎖用來保護(hù)數(shù)據(jù)庫內(nèi)部的數(shù)據(jù)結(jié)構(gòu),常規(guī)鎖用來保護(hù)數(shù)據(jù)庫對象,相當(dāng)于其他的數(shù)據(jù)庫中的表級鎖和行級鎖。自旋鎖和輕量級鎖沒有死鎖檢測機制,常規(guī)鎖有死鎖檢測機制。
4.1自旋鎖
自旋鎖只有一種模式(互斥模式)。一個數(shù)據(jù)庫進(jìn)程持有自旋鎖的時間應(yīng)該非常短。
在使用自旋鎖以前,應(yīng)當(dāng)使用宏S_INIT_LOCK(lock)初始化自旋鎖,使用宏S_LOCK(lock)得到自旋鎖,使用宏S_UNLOCK(lock)釋放自旋鎖。這三個宏在include/storage/spin.h中定義:
#define SpinLockInit(lock) S_INIT_LOCK(lock)
#define SpinLockAcquire(lock) S_LOCK(lock)
#define SpinLockRelease(lock) S_UNLOCK(lock)
#define SpinLockFree(lock) S_LOCK_FREE(lock)
為提高執(zhí)行的效率,得到自旋鎖的核心步驟test and set操作采用匯編語言實現(xiàn),所以在不同平臺上的實現(xiàn)代碼是不一樣的,X86平臺上的test and set操作的實現(xiàn)代碼如下,位于include/storage/s_lock.h文件中:
tas(volatile slock_t *lock)
{
register slock_t _res = 1;
/*
* Use a non-locking test before asserting the bus lock. Note that the
* extra test appears to be a small loss on some x86 platforms and a small
* win on others; it's by no means clear that we should keep it.
*/
__asm__ __volatile__(
" cmpb $0,%1 \n"
" jne 1f \n"
" lock \n"
" xchgb %0,%1 \n"
"1: \n"
: "+q"(_res), "+m"(*lock)
:
: "memory", "cc");
return (int) _res;
} |
|