⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sync0sync.c

📁 这是linux下运行的mysql软件包,可用于linux 下安装 php + mysql + apach 的网络配置
💻 C
📖 第 1 页 / 共 3 页
字号:
/******************************************************Mutex, the basic synchronization primitive(c) 1995 Innobase OyCreated 9/5/1995 Heikki Tuuri*******************************************************/#include "sync0sync.h"#ifdef UNIV_NONINL#include "sync0sync.ic"#endif#include "sync0rw.h"#include "buf0buf.h"#include "srv0srv.h"#include "buf0types.h"/*	REASONS FOR IMPLEMENTING THE SPIN LOCK MUTEX	============================================Semaphore operations in operating systems are slow: Solaris on a 1993 Sparctakes 3 microseconds (us) for a lock-unlock pair and Windows NT on a 1995Pentium takes 20 microseconds for a lock-unlock pair. Therefore, we have toimplement our own efficient spin lock mutex. Future operating systems mayprovide efficient spin locks, but we cannot count on that.Another reason for implementing a spin lock is that on multiprocessor systemsit can be more efficient for a processor to run a loop waiting for the semaphore to be released than to switch to a different thread. A thread switchtakes 25 us on both platforms mentioned above. See Gray and Reuter's bookTransaction processing for background.How long should the spin loop last before suspending the thread? On auniprocessor, spinning does not help at all, because if the thread owning themutex is not executing, it cannot be released. Spinning actually wastesresources. On a multiprocessor, we do not know if the thread owning the mutex isexecuting or not. Thus it would make sense to spin as long as the operationguarded by the mutex would typically last assuming that the thread isexecuting. If the mutex is not released by that time, we may assume that thethread owning the mutex is not executing and suspend the waiting thread.A typical operation (where no i/o involved) guarded by a mutex or a read-writelock may last 1 - 20 us on the current Pentium platform. The longestoperations are the binary searches on an index node.We conclude that the best choice is to set the spin time at 20 us. Then thesystem should work well on a multiprocessor. On a uniprocessor we have tomake sure that thread swithches due to mutex collisions are not frequent,i.e., they do not happen every 100 us or so, because that wastes too muchresources. If the thread switches are not frequent, the 20 us wasted in spinloop is not too much. Empirical studies on the effect of spin time should be done for differentplatforms.		IMPLEMENTATION OF THE MUTEX	===========================For background, see Curt Schimmel's book on Unix implementation on modernarchitectures. The key points in the implementation are atomicity andserialization of memory accesses. The test-and-set instruction (XCHG inPentium) must be atomic. As new processors may have weak memory models, alsoserialization of memory references may be necessary. The successor of Pentium,P6, has at least one mode where the memory model is weak. As far as we know,in Pentium all memory accesses are serialized in the program order and we donot have to worry about the memory model. On other processors there arespecial machine instructions called a fence, memory barrier, or storagebarrier (STBAR in Sparc), which can be used to serialize the memory accessesto happen in program order relative to the fence instruction.Leslie Lamport has devised a "bakery algorithm" to implement a mutex withoutthe atomic test-and-set, but his algorithm should be modified for weak memorymodels. We do not use Lamport's algorithm, because we guess it is slower thanthe atomic test-and-set.Our mutex implementation works as follows: After that we perform the atomictest-and-set instruction on the memory word. If the test returns zero, weknow we got the lock first. If the test returns not zero, some other threadwas quicker and got the lock: then we spin in a loop reading the memory word,waiting it to become zero. It is wise to just read the word in the loop, notperform numerous test-and-set instructions, because they generate memorytraffic between the cache and the main memory. The read loop can just accessthe cache, saving bus bandwidth.If we cannot acquire the mutex lock in the specified time, we reserve a cellin the wait array, set the waiters byte in the mutex to 1. To avoid a racecondition, after setting the waiters byte and before suspending the waitingthread, we still have to check that the mutex is reserved, because it mayhave happened that the thread which was holding the mutex has just releasedit and did not see the waiters byte set to 1, a case which would lead theother thread to an infinite wait.LEMMA 1: After a thread resets the event of the cell it reserves for waiting========for a mutex, some thread will eventually call sync_array_signal_object withthe mutex as an argument. Thus no infinite wait is possible.Proof:	After making the reservation the thread sets the waiters field in themutex to 1. Then it checks that the mutex is still reserved by some thread,or it reserves the mutex for itself. In any case, some thread (which may bealso some earlier thread, not necessarily the one currently holding the mutex)will set the waiters field to 0 in mutex_exit, and then callsync_array_signal_object with the mutex as an argument. Q.E.D. */ulint	sync_dummy			= 0;/* The number of system calls made in this module. Intended for performancemonitoring. */ulint	mutex_system_call_count		= 0;/* Number of spin waits on mutexes: for performance monitoring */ulint	mutex_spin_round_count		= 0;ulint	mutex_spin_wait_count		= 0;ulint	mutex_os_wait_count		= 0;ulint	mutex_exit_count		= 0;/* The global array of wait cells for implementation of the database's ownmutexes and read-write locks */sync_array_t*	sync_primary_wait_array;/* This variable is set to TRUE when sync_init is called */ibool	sync_initialized	= FALSE;typedef struct sync_level_struct	sync_level_t;typedef struct sync_thread_struct	sync_thread_t;/* The latch levels currently owned by threads are stored in this datastructure; the size of this array is OS_THREAD_MAX_N */sync_thread_t*	sync_thread_level_arrays;/* Mutex protecting sync_thread_level_arrays */mutex_t	sync_thread_mutex;/* Global list of database mutexes (not OS mutexes) created. */ut_list_base_node_t  mutex_list;/* Mutex protecting the mutex_list variable */mutex_t mutex_list_mutex;/* Latching order checks start when this is set TRUE */ibool	sync_order_checks_on	= FALSE;/* Dummy mutex used to implement mutex_fence */mutex_t	dummy_mutex_for_fence;struct sync_thread_struct{	os_thread_id_t	id;	/* OS thread id */	sync_level_t*	levels;	/* level array for this thread; if this is NULL				this slot is unused */};/* Number of slots reserved for each OS thread in the sync level array */#define SYNC_THREAD_N_LEVELS	10000struct sync_level_struct{	void*	latch;	/* pointer to a mutex or an rw-lock; NULL means that			the slot is empty */	ulint	level;	/* level of the latch in the latching order */};/**********************************************************************A noninlined function that reserves a mutex. In ha_innodb.cc we have disabledinlining of InnoDB functions, and no inlined functions should be called fromthere. That is why we need to duplicate the inlined function here. */voidmutex_enter_noninline(/*==================*/	mutex_t*	mutex)	/* in: mutex */{	mutex_enter(mutex);}/**********************************************************************Releases a mutex. */voidmutex_exit_noninline(/*=================*/	mutex_t*	mutex)	/* in: mutex */{	mutex_exit(mutex);}/**********************************************************************Creates, or rather, initializes a mutex object in a specified memorylocation (which must be appropriately aligned). The mutex is initializedin the reset state. Explicit freeing of the mutex with mutex_free isnecessary only if the memory block containing it is freed. */voidmutex_create_func(/*==============*/	mutex_t*	mutex,		/* in: pointer to memory */	const char*	cfile_name,	/* in: file name where created */  ulint cline,  /* in: file line where created */  const char* cmutex_name)  /* in: mutex name */{#if defined(_WIN32) && defined(UNIV_CAN_USE_X86_ASSEMBLER)	mutex_reset_lock_word(mutex);#else		os_fast_mutex_init(&(mutex->os_fast_mutex));	mutex->lock_word = 0;#endif	mutex_set_waiters(mutex, 0);	mutex->magic_n = MUTEX_MAGIC_N;#ifdef UNIV_SYNC_DEBUG	mutex->line = 0;	mutex->file_name = "not yet reserved";#endif /* UNIV_SYNC_DEBUG */	mutex->level = SYNC_LEVEL_NONE;	mutex->cfile_name = cfile_name;	mutex->cline = cline;#ifndef UNIV_HOTBACKUP  mutex->cmutex_name=     cmutex_name;  mutex->count_using=     0;  mutex->mutex_type=      0;  mutex->lspent_time=     0;  mutex->lmax_spent_time=     0;  mutex->count_spin_loop= 0;  mutex->count_spin_rounds=   0;   mutex->count_os_wait=   0;  mutex->count_os_yield=  0;#endif /* !UNIV_HOTBACKUP */		/* Check that lock_word is aligned; this is important on Intel */	ut_ad(((ulint)(&(mutex->lock_word))) % 4 == 0);	/* NOTE! The very first mutexes are not put to the mutex list */	if ((mutex == &mutex_list_mutex) || (mutex == &sync_thread_mutex)) {	    	return;	}		mutex_enter(&mutex_list_mutex);        if (UT_LIST_GET_LEN(mutex_list) > 0) {                ut_a(UT_LIST_GET_FIRST(mutex_list)->magic_n == MUTEX_MAGIC_N);        }	UT_LIST_ADD_FIRST(list, mutex_list, mutex);	mutex_exit(&mutex_list_mutex);}/**********************************************************************Calling this function is obligatory only if the memory buffer containingthe mutex is freed. Removes a mutex object from the mutex list. The mutexis checked to be in the reset state. */voidmutex_free(/*=======*/	mutex_t*	mutex)	/* in: mutex */{#ifdef UNIV_DEBUG	ut_a(mutex_validate(mutex));#endif /* UNIV_DEBUG */	ut_a(mutex_get_lock_word(mutex) == 0);	ut_a(mutex_get_waiters(mutex) == 0);		if (mutex != &mutex_list_mutex && mutex != &sync_thread_mutex) {	        mutex_enter(&mutex_list_mutex);		if (UT_LIST_GET_PREV(list, mutex)) {			ut_a(UT_LIST_GET_PREV(list, mutex)->magic_n							== MUTEX_MAGIC_N);		}		if (UT_LIST_GET_NEXT(list, mutex)) {			ut_a(UT_LIST_GET_NEXT(list, mutex)->magic_n							== MUTEX_MAGIC_N);		}        	        UT_LIST_REMOVE(list, mutex_list, mutex);		mutex_exit(&mutex_list_mutex);	}#if !defined(_WIN32) || !defined(UNIV_CAN_USE_X86_ASSEMBLER) 	os_fast_mutex_free(&(mutex->os_fast_mutex));#endif	/* If we free the mutex protecting the mutex list (freeing is	not necessary), we have to reset the magic number AFTER removing	it from the list. */		mutex->magic_n = 0;}/************************************************************************Tries to lock the mutex for the current thread. If the lock is not acquiredimmediately, returns with return value 1. */ulintmutex_enter_nowait(/*===============*/					/* out: 0 if succeed, 1 if not */	mutex_t*	mutex,		/* in: pointer to mutex */	const char*	file_name __attribute__((unused)),					/* in: file name where mutex					requested */	ulint		line __attribute__((unused)))					/* in: line where requested */{	ut_ad(mutex_validate(mutex));	if (!mutex_test_and_set(mutex)) {#ifdef UNIV_SYNC_DEBUG		mutex_set_debug_info(mutex, file_name, line);#endif		return(0);	/* Succeeded! */	}	return(1);}/**********************************************************************Checks that the mutex has been initialized. */iboolmutex_validate(/*===========*/	mutex_t*	mutex){	ut_a(mutex);	ut_a(mutex->magic_n == MUTEX_MAGIC_N);	return(TRUE);}/**********************************************************************Sets the waiters field in a mutex. */voidmutex_set_waiters(/*==============*/	mutex_t*	mutex,	/* in: mutex */	ulint		n)	/* in: value to set */		{volatile ulint*	ptr;		/* declared volatile to ensure that				the value is stored to memory */	ut_ad(mutex);	ptr = &(mutex->waiters);	*ptr = n;		/* Here we assume that the write of a single				word in memory is atomic */}/**********************************************************************Reserves a mutex for the current thread. If the mutex is reserved, thefunction spins a preset time (controlled by SYNC_SPIN_ROUNDS), waitingfor the mutex before suspending the thread. */voidmutex_spin_wait(/*============*/  mutex_t*  mutex,      /* in: pointer to mutex */  const char*    file_name,   /* in: file name where                             mutex requested */  ulint line) /* in: line where requested */{  ulint    index; /* index of the reserved wait cell */  ulint    i;     /* spin round count */#ifndef UNIV_HOTBACKUP  ib_longlong lstart_time = 0, lfinish_time; /* for timing os_wait */  ulint ltime_diff;  ulint sec;  ulint ms;  uint timer_started = 0;#endif /* !UNIV_HOTBACKUP */  ut_ad(mutex);mutex_loop:  i = 0;/* Spin waiting for the lock word to become zero. Note that we do not  have to assume that the read access to the lock word is atomic, as the  actual locking is always committed with atomic test-and-set. In  reality, however, all processors probably have an atomic read of a  memory word. */spin_loop:#ifndef UNIV_HOTBACKUP  mutex_spin_wait_count++;  mutex->count_spin_loop++;#endif /* !UNIV_HOTBACKUP */  while (mutex_get_lock_word(mutex) != 0 && i < SYNC_SPIN_ROUNDS)  {    if (srv_spin_wait_delay)    {      ut_delay(ut_rnd_interval(0, srv_spin_wait_delay));    }    i++;  }  if (i == SYNC_SPIN_ROUNDS)  {#ifndef UNIV_HOTBACKUP    mutex->count_os_yield++;    if (timed_mutexes == 1 && timer_started==0)    {      ut_usectime(&sec, &ms);      lstart_time= (ib_longlong)sec * 1000000 + ms;      timer_started = 1;    }#endif /* !UNIV_HOTBACKUP */    os_thread_yield();  }#ifdef UNIV_SRV_PRINT_LATCH_WAITS    fprintf(stderr,            "Thread %lu spin wait mutex at %p cfile %s cline %lu rnds %lu\n",            (ulong) os_thread_pf(os_thread_get_curr_id()), mutex,            mutex->cfile_name, (ulong) mutex->cline, (ulong) i);#endif  mutex_spin_round_count += i;#ifndef UNIV_HOTBACKUP  mutex->count_spin_rounds += i;#endif /* !UNIV_HOTBACKUP */  if (mutex_test_and_set(mutex) == 0)  {    /* Succeeded! */#ifdef UNIV_SYNC_DEBUG    mutex_set_debug_info(mutex, file_name, line);#endif    goto finish_timing;  }  /* We may end up with a situation where lock_word is  0 but the OS fast mutex is still reserved. On FreeBSD  the OS does not seem to schedule a thread which is constantly

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -