MySQL自旋锁-spin lock

自旋锁

标签(空格分隔): innodb


文章目录

  • 自旋锁
      • 简介
      • 数据结构解析
      • 调用
        • try_lock
        • spin_lock

简介

Innodb中大量使用自旋锁来避免锁等待时的上下文切换,影响性能的问题。自旋锁分为加锁和解锁两个过程,其中加锁分为尝试加锁与自旋的过程。

数据结构解析

其上层调用方式一般为如下:

	mutex_enter(&trx->undo_mutex);

mutex_enter宏定义如下

#define mutex_enter(M)			(M)->enter(			\
					srv_n_spin_wait_rounds,		\
					srv_spin_wait_delay,		\
					__FILE__, __LINE__)

所以根据不同的mutex类型,有不同的实现。有点类似与C++中的多态。
而如上示例中的undo_mutex定义如下

UndoMutex	undo_mutex;	/*!< mutex protecting the fields in this
					section (down to undo_no_arr), EXCEPT
					last_sql_stat_start, which can be
					accessed only when we know that there
					cannot be any activity in the undo
					logs! */

UndoMutex的声明为

typedef ib_mutex_t UndoMutex;

ib_mutex_t的声明为

typedef SyncArrayMutex ib_mutex_t;

SyncArrayMutex的声明为

UT_MUTEX_TYPE(TTASEventMutex, GenericPolicy, SyncArrayMutex);

UT_MUTEX_TYPE的宏定义为

/** Create a typedef using the MutexType
@param[in]	M		Mutex type
@param[in[	P		Policy type
@param[in]	T		The resulting typedef alias */

#define UT_MUTEX_TYPE(M, P, T) typedef PolicyMutex > T;

展开就是

typedef PolicyMutex > SyncArrayMutex;

其中PolicyMutex的模版定义为

template 
struct PolicyMutex
{
}

TTASEventMutex的模版定义为

template