Team Ai
Modelpublic

AryaWu/sqlite

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
mutex_unix.c395 linesDownload Raw Back to src
1/*2** 2007 August 283**4** The author disclaims copyright to this source code.  In place of5** 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 pthreads13*/14#include "sqliteInt.h"15 16/*17** The code in this file is only used if we are compiling threadsafe18** under unix with pthreads.19**20** Note that this implementation requires a version of pthreads that21** supports recursive mutexes.22*/23#ifdef SQLITE_MUTEX_PTHREADS24 25#include <pthread.h>26 27/*28** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields29** are necessary under two conditions:  (1) Debug builds and (2) using30** home-grown mutexes.  Encapsulate these conditions into a single #define.31*/32#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)33# define SQLITE_MUTEX_NREF 134#else35# define SQLITE_MUTEX_NREF 036#endif37 38/*39** Each recursive mutex is an instance of the following structure.40*/41struct sqlite3_mutex {42  pthread_mutex_t mutex;     /* Mutex controlling the lock */43#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)44  int id;                    /* Mutex type */45#endif46#if SQLITE_MUTEX_NREF47  volatile int nRef;         /* Number of entrances */48  volatile pthread_t owner;  /* Thread that is within this mutex */49  int trace;                 /* True to trace changes */50#endif51};52#if SQLITE_MUTEX_NREF53# define SQLITE3_MUTEX_INITIALIZER(id) \54     {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}55#elif defined(SQLITE_ENABLE_API_ARMOR)56# define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }57#else58#define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }59#endif60 61/*62** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are63** intended for use only inside assert() statements.  On some platforms,64** there might be race conditions that can cause these routines to65** deliver incorrect results.  In particular, if pthread_equal() is66** not an atomic operation, then these routines might delivery67** incorrect results.  On most platforms, pthread_equal() is a68** comparison of two integers and is therefore atomic.  But we are69** told that HPUX is not such a platform.  If so, then these routines70** will not always work correctly on HPUX.71**72** On those platforms where pthread_equal() is not atomic, SQLite73** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to74** make sure no assert() statements are evaluated and hence these75** routines are never called.76*/77#if !defined(NDEBUG) || defined(SQLITE_DEBUG)78static int pthreadMutexHeld(sqlite3_mutex *p){79  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));80}81static int pthreadMutexNotheld(sqlite3_mutex *p){82  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;83}84#endif85 86/*87** Try to provide a memory barrier operation, needed for initialization88** and also for the implementation of xShmBarrier in the VFS in cases89** where SQLite is compiled without mutexes.90*/91void sqlite3MemoryBarrier(void){92#if defined(SQLITE_MEMORY_BARRIER)93  SQLITE_MEMORY_BARRIER;94#elif defined(__GNUC__) && GCC_VERSION>=400100095  __sync_synchronize();96#endif97}98 99/*100** Initialize and deinitialize the mutex subsystem.101*/102static int pthreadMutexInit(void){ return SQLITE_OK; }103static int pthreadMutexEnd(void){ return SQLITE_OK; }104 105/*106** The sqlite3_mutex_alloc() routine allocates a new107** mutex and returns a pointer to it.  If it returns NULL108** that means that a mutex could not be allocated.  SQLite109** will unwind its stack and return an error.  The argument110** to sqlite3_mutex_alloc() is one of these integer constants:111**112** <ul>113** <li>  SQLITE_MUTEX_FAST114** <li>  SQLITE_MUTEX_RECURSIVE115** <li>  SQLITE_MUTEX_STATIC_MAIN116** <li>  SQLITE_MUTEX_STATIC_MEM117** <li>  SQLITE_MUTEX_STATIC_OPEN118** <li>  SQLITE_MUTEX_STATIC_PRNG119** <li>  SQLITE_MUTEX_STATIC_LRU120** <li>  SQLITE_MUTEX_STATIC_PMEM121** <li>  SQLITE_MUTEX_STATIC_APP1122** <li>  SQLITE_MUTEX_STATIC_APP2123** <li>  SQLITE_MUTEX_STATIC_APP3124** <li>  SQLITE_MUTEX_STATIC_VFS1125** <li>  SQLITE_MUTEX_STATIC_VFS2126** <li>  SQLITE_MUTEX_STATIC_VFS3127** </ul>128**129** The first two constants cause sqlite3_mutex_alloc() to create130** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE131** is used but not necessarily so when SQLITE_MUTEX_FAST is used.132** The mutex implementation does not need to make a distinction133** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does134** not want to.  But SQLite will only request a recursive mutex in135** cases where it really needs one.  If a faster non-recursive mutex136** implementation is available on the host platform, the mutex subsystem137** might return such a mutex in response to SQLITE_MUTEX_FAST.138**139** The other allowed parameters to sqlite3_mutex_alloc() each return140** a pointer to a static preexisting mutex.  Six static mutexes are141** used by the current version of SQLite.  Future versions of SQLite142** may add additional static mutexes.  Static mutexes are for internal143** use by SQLite only.  Applications that use SQLite mutexes should144** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or145** SQLITE_MUTEX_RECURSIVE.146**147** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST148** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()149** returns a different mutex on every call.  But for the static150** mutex types, the same mutex is returned on every call that has151** the same type number.152*/153static sqlite3_mutex *pthreadMutexAlloc(int iType){154  static sqlite3_mutex staticMutexes[] = {155    SQLITE3_MUTEX_INITIALIZER(2),156    SQLITE3_MUTEX_INITIALIZER(3),157    SQLITE3_MUTEX_INITIALIZER(4),158    SQLITE3_MUTEX_INITIALIZER(5),159    SQLITE3_MUTEX_INITIALIZER(6),160    SQLITE3_MUTEX_INITIALIZER(7),161    SQLITE3_MUTEX_INITIALIZER(8),162    SQLITE3_MUTEX_INITIALIZER(9),163    SQLITE3_MUTEX_INITIALIZER(10),164    SQLITE3_MUTEX_INITIALIZER(11),165    SQLITE3_MUTEX_INITIALIZER(12),166    SQLITE3_MUTEX_INITIALIZER(13)167  };168  sqlite3_mutex *p;169  switch( iType ){170    case SQLITE_MUTEX_RECURSIVE: {171      p = sqlite3MallocZero( sizeof(*p) );172      if( p ){173#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX174        /* If recursive mutexes are not available, we will have to175        ** build our own.  See below. */176        pthread_mutex_init(&p->mutex, 0);177#else178        /* Use a recursive mutex if it is available */179        pthread_mutexattr_t recursiveAttr;180        pthread_mutexattr_init(&recursiveAttr);181        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);182        pthread_mutex_init(&p->mutex, &recursiveAttr);183        pthread_mutexattr_destroy(&recursiveAttr);184#endif185#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)186        p->id = SQLITE_MUTEX_RECURSIVE;187#endif188      }189      break;190    }191    case SQLITE_MUTEX_FAST: {192      p = sqlite3MallocZero( sizeof(*p) );193      if( p ){194        pthread_mutex_init(&p->mutex, 0);195#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)196        p->id = SQLITE_MUTEX_FAST;197#endif198      }199      break;200    }201    default: {202#ifdef SQLITE_ENABLE_API_ARMOR203      if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){204        (void)SQLITE_MISUSE_BKPT;205        return 0;206      }207#endif208      p = &staticMutexes[iType-2];209      break;210    }211  }212#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)213  assert( p==0 || p->id==iType );214#endif215  return p;216}217 218 219/*220** This routine deallocates a previously221** allocated mutex.  SQLite is careful to deallocate every222** mutex that it allocates.223*/224static void pthreadMutexFree(sqlite3_mutex *p){225  assert( p->nRef==0 );226#ifdef SQLITE_ENABLE_API_ARMOR227  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )228#endif229  {230    pthread_mutex_destroy(&p->mutex);231    sqlite3_free(p);232  }233#ifdef SQLITE_ENABLE_API_ARMOR234  else{235    (void)SQLITE_MISUSE_BKPT;236  }237#endif238}239 240/*241** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt242** to enter a mutex.  If another thread is already within the mutex,243** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return244** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK245** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can246** be entered multiple times by the same thread.  In such cases the,247** mutex must be exited an equal number of times before another thread248** can enter.  If the same thread tries to enter any other kind of mutex249** more than once, the behavior is undefined.250*/251static void pthreadMutexEnter(sqlite3_mutex *p){252  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );253 254#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX255  /* If recursive mutexes are not available, then we have to grow256  ** our own.  This implementation assumes that pthread_equal()257  ** is atomic - that it cannot be deceived into thinking self258  ** and p->owner are equal if p->owner changes between two values259  ** that are not equal to self while the comparison is taking place.260  ** This implementation also assumes a coherent cache - that261  ** separate processes cannot read different values from the same262  ** address at the same time.  If either of these two conditions263  ** are not met, then the mutexes will fail and problems will result.264  */265  {266    pthread_t self = pthread_self();267    if( p->nRef>0 && pthread_equal(p->owner, self) ){268      p->nRef++;269    }else{270      pthread_mutex_lock(&p->mutex);271      assert( p->nRef==0 );272      p->owner = self;273      p->nRef = 1;274    }275  }276#else277  /* Use the built-in recursive mutexes if they are available.278  */279  pthread_mutex_lock(&p->mutex);280#if SQLITE_MUTEX_NREF281  assert( p->nRef>0 || p->owner==0 );282  p->owner = pthread_self();283  p->nRef++;284#endif285#endif286 287#ifdef SQLITE_DEBUG288  if( p->trace ){289    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);290  }291#endif292}293static int pthreadMutexTry(sqlite3_mutex *p){294  int rc;295  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );296 297#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX298  /* If recursive mutexes are not available, then we have to grow299  ** our own.  This implementation assumes that pthread_equal()300  ** is atomic - that it cannot be deceived into thinking self301  ** and p->owner are equal if p->owner changes between two values302  ** that are not equal to self while the comparison is taking place.303  ** This implementation also assumes a coherent cache - that304  ** separate processes cannot read different values from the same305  ** address at the same time.  If either of these two conditions306  ** are not met, then the mutexes will fail and problems will result.307  */308  {309    pthread_t self = pthread_self();310    if( p->nRef>0 && pthread_equal(p->owner, self) ){311      p->nRef++;312      rc = SQLITE_OK;313    }else if( pthread_mutex_trylock(&p->mutex)==0 ){314      assert( p->nRef==0 );315      p->owner = self;316      p->nRef = 1;317      rc = SQLITE_OK;318    }else{319      rc = SQLITE_BUSY;320    }321  }322#else323  /* Use the built-in recursive mutexes if they are available.324  */325  if( pthread_mutex_trylock(&p->mutex)==0 ){326#if SQLITE_MUTEX_NREF327    p->owner = pthread_self();328    p->nRef++;329#endif330    rc = SQLITE_OK;331  }else{332    rc = SQLITE_BUSY;333  }334#endif335 336#ifdef SQLITE_DEBUG337  if( rc==SQLITE_OK && p->trace ){338    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);339  }340#endif341  return rc;342}343 344/*345** The sqlite3_mutex_leave() routine exits a mutex that was346** previously entered by the same thread.  The behavior347** is undefined if the mutex is not currently entered or348** is not currently allocated.  SQLite will never do either.349*/350static void pthreadMutexLeave(sqlite3_mutex *p){351  assert( pthreadMutexHeld(p) );352#if SQLITE_MUTEX_NREF353  p->nRef--;354  if( p->nRef==0 ) p->owner = 0;355#endif356  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );357 358#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX359  if( p->nRef==0 ){360    pthread_mutex_unlock(&p->mutex);361  }362#else363  pthread_mutex_unlock(&p->mutex);364#endif365 366#ifdef SQLITE_DEBUG367  if( p->trace ){368    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);369  }370#endif371}372 373sqlite3_mutex_methods const *sqlite3DefaultMutex(void){374  static const sqlite3_mutex_methods sMutex = {375    pthreadMutexInit,376    pthreadMutexEnd,377    pthreadMutexAlloc,378    pthreadMutexFree,379    pthreadMutexEnter,380    pthreadMutexTry,381    pthreadMutexLeave,382#ifdef SQLITE_DEBUG383    pthreadMutexHeld,384    pthreadMutexNotheld385#else386    0,387    0388#endif389  };390 391  return &sMutex;392}393 394#endif /* SQLITE_MUTEX_PTHREADS */395