mutex_unix.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. ** 2007 August 28
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. ** This file contains the C functions that implement mutexes for pthreads
  13. */
  14. #include "sqliteInt.h"
  15. /*
  16. ** The code in this file is only used if we are compiling threadsafe
  17. ** under unix with pthreads.
  18. **
  19. ** Note that this implementation requires a version of pthreads that
  20. ** supports recursive mutexes.
  21. */
  22. #ifdef SQLITE_MUTEX_PTHREADS
  23. #include <pthread.h>
  24. /*
  25. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  26. ** are necessary under two condidtions: (1) Debug builds and (2) using
  27. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  28. */
  29. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  30. # define SQLITE_MUTEX_NREF 1
  31. #else
  32. # define SQLITE_MUTEX_NREF 0
  33. #endif
  34. /*
  35. ** Each recursive mutex is an instance of the following structure.
  36. */
  37. struct sqlite3_mutex {
  38. pthread_mutex_t mutex; /* Mutex controlling the lock */
  39. #if SQLITE_MUTEX_NREF
  40. int id; /* Mutex type */
  41. volatile int nRef; /* Number of entrances */
  42. volatile pthread_t owner; /* Thread that is within this mutex */
  43. int trace; /* True to trace changes */
  44. #endif
  45. };
  46. #if SQLITE_MUTEX_NREF
  47. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  48. #else
  49. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  50. #endif
  51. /*
  52. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  53. ** intended for use only inside assert() statements. On some platforms,
  54. ** there might be race conditions that can cause these routines to
  55. ** deliver incorrect results. In particular, if pthread_equal() is
  56. ** not an atomic operation, then these routines might delivery
  57. ** incorrect results. On most platforms, pthread_equal() is a
  58. ** comparison of two integers and is therefore atomic. But we are
  59. ** told that HPUX is not such a platform. If so, then these routines
  60. ** will not always work correctly on HPUX.
  61. **
  62. ** On those platforms where pthread_equal() is not atomic, SQLite
  63. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  64. ** make sure no assert() statements are evaluated and hence these
  65. ** routines are never called.
  66. */
  67. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  68. static int pthreadMutexHeld(sqlite3_mutex *p){
  69. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  70. }
  71. static int pthreadMutexNotheld(sqlite3_mutex *p){
  72. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  73. }
  74. #endif
  75. /*
  76. ** Initialize and deinitialize the mutex subsystem.
  77. */
  78. static int pthreadMutexInit(void){ return SQLITE_OK; }
  79. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  80. /*
  81. ** The sqlite3_mutex_alloc() routine allocates a new
  82. ** mutex and returns a pointer to it. If it returns NULL
  83. ** that means that a mutex could not be allocated. SQLite
  84. ** will unwind its stack and return an error. The argument
  85. ** to sqlite3_mutex_alloc() is one of these integer constants:
  86. **
  87. ** <ul>
  88. ** <li> SQLITE_MUTEX_FAST
  89. ** <li> SQLITE_MUTEX_RECURSIVE
  90. ** <li> SQLITE_MUTEX_STATIC_MASTER
  91. ** <li> SQLITE_MUTEX_STATIC_MEM
  92. ** <li> SQLITE_MUTEX_STATIC_MEM2
  93. ** <li> SQLITE_MUTEX_STATIC_PRNG
  94. ** <li> SQLITE_MUTEX_STATIC_LRU
  95. ** <li> SQLITE_MUTEX_STATIC_PMEM
  96. ** </ul>
  97. **
  98. ** The first two constants cause sqlite3_mutex_alloc() to create
  99. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  100. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  101. ** The mutex implementation does not need to make a distinction
  102. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  103. ** not want to. But SQLite will only request a recursive mutex in
  104. ** cases where it really needs one. If a faster non-recursive mutex
  105. ** implementation is available on the host platform, the mutex subsystem
  106. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  107. **
  108. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  109. ** a pointer to a static preexisting mutex. Six static mutexes are
  110. ** used by the current version of SQLite. Future versions of SQLite
  111. ** may add additional static mutexes. Static mutexes are for internal
  112. ** use by SQLite only. Applications that use SQLite mutexes should
  113. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  114. ** SQLITE_MUTEX_RECURSIVE.
  115. **
  116. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  117. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  118. ** returns a different mutex on every call. But for the static
  119. ** mutex types, the same mutex is returned on every call that has
  120. ** the same type number.
  121. */
  122. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  123. static sqlite3_mutex staticMutexes[] = {
  124. SQLITE3_MUTEX_INITIALIZER,
  125. SQLITE3_MUTEX_INITIALIZER,
  126. SQLITE3_MUTEX_INITIALIZER,
  127. SQLITE3_MUTEX_INITIALIZER,
  128. SQLITE3_MUTEX_INITIALIZER,
  129. SQLITE3_MUTEX_INITIALIZER
  130. };
  131. sqlite3_mutex *p;
  132. switch( iType ){
  133. case SQLITE_MUTEX_RECURSIVE: {
  134. p = sqlite3MallocZero( sizeof(*p) );
  135. if( p ){
  136. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  137. /* If recursive mutexes are not available, we will have to
  138. ** build our own. See below. */
  139. pthread_mutex_init(&p->mutex, 0);
  140. #else
  141. /* Use a recursive mutex if it is available */
  142. pthread_mutexattr_t recursiveAttr;
  143. pthread_mutexattr_init(&recursiveAttr);
  144. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  145. pthread_mutex_init(&p->mutex, &recursiveAttr);
  146. pthread_mutexattr_destroy(&recursiveAttr);
  147. #endif
  148. #if SQLITE_MUTEX_NREF
  149. p->id = iType;
  150. #endif
  151. }
  152. break;
  153. }
  154. case SQLITE_MUTEX_FAST: {
  155. p = sqlite3MallocZero( sizeof(*p) );
  156. if( p ){
  157. #if SQLITE_MUTEX_NREF
  158. p->id = iType;
  159. #endif
  160. pthread_mutex_init(&p->mutex, 0);
  161. }
  162. break;
  163. }
  164. default: {
  165. assert( iType-2 >= 0 );
  166. assert( iType-2 < ArraySize(staticMutexes) );
  167. p = &staticMutexes[iType-2];
  168. #if SQLITE_MUTEX_NREF
  169. p->id = iType;
  170. #endif
  171. break;
  172. }
  173. }
  174. return p;
  175. }
  176. /*
  177. ** This routine deallocates a previously
  178. ** allocated mutex. SQLite is careful to deallocate every
  179. ** mutex that it allocates.
  180. */
  181. static void pthreadMutexFree(sqlite3_mutex *p){
  182. assert( p->nRef==0 );
  183. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  184. pthread_mutex_destroy(&p->mutex);
  185. sqlite3_free(p);
  186. }
  187. /*
  188. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  189. ** to enter a mutex. If another thread is already within the mutex,
  190. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  191. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  192. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  193. ** be entered multiple times by the same thread. In such cases the,
  194. ** mutex must be exited an equal number of times before another thread
  195. ** can enter. If the same thread tries to enter any other kind of mutex
  196. ** more than once, the behavior is undefined.
  197. */
  198. static void pthreadMutexEnter(sqlite3_mutex *p){
  199. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  200. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  201. /* If recursive mutexes are not available, then we have to grow
  202. ** our own. This implementation assumes that pthread_equal()
  203. ** is atomic - that it cannot be deceived into thinking self
  204. ** and p->owner are equal if p->owner changes between two values
  205. ** that are not equal to self while the comparison is taking place.
  206. ** This implementation also assumes a coherent cache - that
  207. ** separate processes cannot read different values from the same
  208. ** address at the same time. If either of these two conditions
  209. ** are not met, then the mutexes will fail and problems will result.
  210. */
  211. {
  212. pthread_t self = pthread_self();
  213. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  214. p->nRef++;
  215. }else{
  216. pthread_mutex_lock(&p->mutex);
  217. assert( p->nRef==0 );
  218. p->owner = self;
  219. p->nRef = 1;
  220. }
  221. }
  222. #else
  223. /* Use the built-in recursive mutexes if they are available.
  224. */
  225. pthread_mutex_lock(&p->mutex);
  226. #if SQLITE_MUTEX_NREF
  227. assert( p->nRef>0 || p->owner==0 );
  228. p->owner = pthread_self();
  229. p->nRef++;
  230. #endif
  231. #endif
  232. #ifdef SQLITE_DEBUG
  233. if( p->trace ){
  234. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  235. }
  236. #endif
  237. }
  238. static int pthreadMutexTry(sqlite3_mutex *p){
  239. int rc;
  240. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  241. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  242. /* If recursive mutexes are not available, then we have to grow
  243. ** our own. This implementation assumes that pthread_equal()
  244. ** is atomic - that it cannot be deceived into thinking self
  245. ** and p->owner are equal if p->owner changes between two values
  246. ** that are not equal to self while the comparison is taking place.
  247. ** This implementation also assumes a coherent cache - that
  248. ** separate processes cannot read different values from the same
  249. ** address at the same time. If either of these two conditions
  250. ** are not met, then the mutexes will fail and problems will result.
  251. */
  252. {
  253. pthread_t self = pthread_self();
  254. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  255. p->nRef++;
  256. rc = SQLITE_OK;
  257. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  258. assert( p->nRef==0 );
  259. p->owner = self;
  260. p->nRef = 1;
  261. rc = SQLITE_OK;
  262. }else{
  263. rc = SQLITE_BUSY;
  264. }
  265. }
  266. #else
  267. /* Use the built-in recursive mutexes if they are available.
  268. */
  269. if( pthread_mutex_trylock(&p->mutex)==0 ){
  270. #if SQLITE_MUTEX_NREF
  271. p->owner = pthread_self();
  272. p->nRef++;
  273. #endif
  274. rc = SQLITE_OK;
  275. }else{
  276. rc = SQLITE_BUSY;
  277. }
  278. #endif
  279. #ifdef SQLITE_DEBUG
  280. if( rc==SQLITE_OK && p->trace ){
  281. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  282. }
  283. #endif
  284. return rc;
  285. }
  286. /*
  287. ** The sqlite3_mutex_leave() routine exits a mutex that was
  288. ** previously entered by the same thread. The behavior
  289. ** is undefined if the mutex is not currently entered or
  290. ** is not currently allocated. SQLite will never do either.
  291. */
  292. static void pthreadMutexLeave(sqlite3_mutex *p){
  293. assert( pthreadMutexHeld(p) );
  294. #if SQLITE_MUTEX_NREF
  295. p->nRef--;
  296. if( p->nRef==0 ) p->owner = 0;
  297. #endif
  298. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  299. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  300. if( p->nRef==0 ){
  301. pthread_mutex_unlock(&p->mutex);
  302. }
  303. #else
  304. pthread_mutex_unlock(&p->mutex);
  305. #endif
  306. #ifdef SQLITE_DEBUG
  307. if( p->trace ){
  308. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  309. }
  310. #endif
  311. }
  312. sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  313. static const sqlite3_mutex_methods sMutex = {
  314. pthreadMutexInit,
  315. pthreadMutexEnd,
  316. pthreadMutexAlloc,
  317. pthreadMutexFree,
  318. pthreadMutexEnter,
  319. pthreadMutexTry,
  320. pthreadMutexLeave,
  321. #ifdef SQLITE_DEBUG
  322. pthreadMutexHeld,
  323. pthreadMutexNotheld
  324. #else
  325. 0,
  326. 0
  327. #endif
  328. };
  329. return &sMutex;
  330. }
  331. #endif /* SQLITE_MUTEX_PTHREADS */