synchronization.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. """Synchronization functions.
  2. File- and mutex-based mutual exclusion synchronizers are provided,
  3. as well as a name-based mutex which locks within an application
  4. based on a string name.
  5. """
  6. import os
  7. import sys
  8. import tempfile
  9. try:
  10. import threading as _threading
  11. except ImportError:
  12. import dummy_threading as _threading
  13. # check for fcntl module
  14. try:
  15. sys.getwindowsversion()
  16. has_flock = False
  17. except:
  18. try:
  19. import fcntl
  20. has_flock = True
  21. except ImportError:
  22. has_flock = False
  23. from beaker import util
  24. from beaker.exceptions import LockError
  25. __all__ = ["file_synchronizer", "mutex_synchronizer", "null_synchronizer",
  26. "NameLock", "_threading"]
  27. class NameLock(object):
  28. """a proxy for an RLock object that is stored in a name based
  29. registry.
  30. Multiple threads can get a reference to the same RLock based on the
  31. name alone, and synchronize operations related to that name.
  32. """
  33. locks = util.WeakValuedRegistry()
  34. class NLContainer(object):
  35. def __init__(self, reentrant):
  36. if reentrant:
  37. self.lock = _threading.RLock()
  38. else:
  39. self.lock = _threading.Lock()
  40. def __call__(self):
  41. return self.lock
  42. def __init__(self, identifier = None, reentrant = False):
  43. if identifier is None:
  44. self._lock = NameLock.NLContainer(reentrant)
  45. else:
  46. self._lock = NameLock.locks.get(identifier, NameLock.NLContainer,
  47. reentrant)
  48. def acquire(self, wait = True):
  49. return self._lock().acquire(wait)
  50. def release(self):
  51. self._lock().release()
  52. _synchronizers = util.WeakValuedRegistry()
  53. def _synchronizer(identifier, cls, **kwargs):
  54. return _synchronizers.sync_get((identifier, cls), cls, identifier, **kwargs)
  55. def file_synchronizer(identifier, **kwargs):
  56. if not has_flock or 'lock_dir' not in kwargs:
  57. return mutex_synchronizer(identifier)
  58. else:
  59. return _synchronizer(identifier, FileSynchronizer, **kwargs)
  60. def mutex_synchronizer(identifier, **kwargs):
  61. return _synchronizer(identifier, ConditionSynchronizer, **kwargs)
  62. class null_synchronizer(object):
  63. def acquire_write_lock(self, wait=True):
  64. return True
  65. def acquire_read_lock(self):
  66. pass
  67. def release_write_lock(self):
  68. pass
  69. def release_read_lock(self):
  70. pass
  71. acquire = acquire_write_lock
  72. release = release_write_lock
  73. class SynchronizerImpl(object):
  74. def __init__(self):
  75. self._state = util.ThreadLocal()
  76. class SyncState(object):
  77. __slots__ = 'reentrantcount', 'writing', 'reading'
  78. def __init__(self):
  79. self.reentrantcount = 0
  80. self.writing = False
  81. self.reading = False
  82. def state(self):
  83. if not self._state.has():
  84. state = SynchronizerImpl.SyncState()
  85. self._state.put(state)
  86. return state
  87. else:
  88. return self._state.get()
  89. state = property(state)
  90. def release_read_lock(self):
  91. state = self.state
  92. if state.writing:
  93. raise LockError("lock is in writing state")
  94. if not state.reading:
  95. raise LockError("lock is not in reading state")
  96. if state.reentrantcount == 1:
  97. self.do_release_read_lock()
  98. state.reading = False
  99. state.reentrantcount -= 1
  100. def acquire_read_lock(self, wait = True):
  101. state = self.state
  102. if state.writing:
  103. raise LockError("lock is in writing state")
  104. if state.reentrantcount == 0:
  105. x = self.do_acquire_read_lock(wait)
  106. if (wait or x):
  107. state.reentrantcount += 1
  108. state.reading = True
  109. return x
  110. elif state.reading:
  111. state.reentrantcount += 1
  112. return True
  113. def release_write_lock(self):
  114. state = self.state
  115. if state.reading:
  116. raise LockError("lock is in reading state")
  117. if not state.writing:
  118. raise LockError("lock is not in writing state")
  119. if state.reentrantcount == 1:
  120. self.do_release_write_lock()
  121. state.writing = False
  122. state.reentrantcount -= 1
  123. release = release_write_lock
  124. def acquire_write_lock(self, wait = True):
  125. state = self.state
  126. if state.reading:
  127. raise LockError("lock is in reading state")
  128. if state.reentrantcount == 0:
  129. x = self.do_acquire_write_lock(wait)
  130. if (wait or x):
  131. state.reentrantcount += 1
  132. state.writing = True
  133. return x
  134. elif state.writing:
  135. state.reentrantcount += 1
  136. return True
  137. acquire = acquire_write_lock
  138. def do_release_read_lock(self):
  139. raise NotImplementedError()
  140. def do_acquire_read_lock(self):
  141. raise NotImplementedError()
  142. def do_release_write_lock(self):
  143. raise NotImplementedError()
  144. def do_acquire_write_lock(self):
  145. raise NotImplementedError()
  146. class FileSynchronizer(SynchronizerImpl):
  147. """a synchronizer which locks using flock().
  148. Adapted for Python/multithreads from Apache::Session::Lock::File,
  149. http://search.cpan.org/src/CWEST/Apache-Session-1.81/Session/Lock/File.pm
  150. This module does not unlink temporary files,
  151. because it interferes with proper locking. This can cause
  152. problems on certain systems (Linux) whose file systems (ext2) do not
  153. perform well with lots of files in one directory. To prevent this
  154. you should use a script to clean out old files from your lock directory.
  155. """
  156. def __init__(self, identifier, lock_dir):
  157. super(FileSynchronizer, self).__init__()
  158. self._filedescriptor = util.ThreadLocal()
  159. if lock_dir is None:
  160. lock_dir = tempfile.gettempdir()
  161. else:
  162. lock_dir = lock_dir
  163. self.filename = util.encoded_path(
  164. lock_dir,
  165. [identifier],
  166. extension='.lock'
  167. )
  168. def _filedesc(self):
  169. return self._filedescriptor.get()
  170. _filedesc = property(_filedesc)
  171. def _open(self, mode):
  172. filedescriptor = self._filedesc
  173. if filedescriptor is None:
  174. filedescriptor = os.open(self.filename, mode)
  175. self._filedescriptor.put(filedescriptor)
  176. return filedescriptor
  177. def do_acquire_read_lock(self, wait):
  178. filedescriptor = self._open(os.O_CREAT | os.O_RDONLY)
  179. if not wait:
  180. try:
  181. fcntl.flock(filedescriptor, fcntl.LOCK_SH | fcntl.LOCK_NB)
  182. return True
  183. except IOError:
  184. os.close(filedescriptor)
  185. self._filedescriptor.remove()
  186. return False
  187. else:
  188. fcntl.flock(filedescriptor, fcntl.LOCK_SH)
  189. return True
  190. def do_acquire_write_lock(self, wait):
  191. filedescriptor = self._open(os.O_CREAT | os.O_WRONLY)
  192. if not wait:
  193. try:
  194. fcntl.flock(filedescriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
  195. return True
  196. except IOError:
  197. os.close(filedescriptor)
  198. self._filedescriptor.remove()
  199. return False
  200. else:
  201. fcntl.flock(filedescriptor, fcntl.LOCK_EX)
  202. return True
  203. def do_release_read_lock(self):
  204. self._release_all_locks()
  205. def do_release_write_lock(self):
  206. self._release_all_locks()
  207. def _release_all_locks(self):
  208. filedescriptor = self._filedesc
  209. if filedescriptor is not None:
  210. fcntl.flock(filedescriptor, fcntl.LOCK_UN)
  211. os.close(filedescriptor)
  212. self._filedescriptor.remove()
  213. class ConditionSynchronizer(SynchronizerImpl):
  214. """a synchronizer using a Condition."""
  215. def __init__(self, identifier):
  216. super(ConditionSynchronizer, self).__init__()
  217. # counts how many asynchronous methods are executing
  218. self.async = 0
  219. # pointer to thread that is the current sync operation
  220. self.current_sync_operation = None
  221. # condition object to lock on
  222. self.condition = _threading.Condition(_threading.Lock())
  223. def do_acquire_read_lock(self, wait = True):
  224. self.condition.acquire()
  225. try:
  226. # see if a synchronous operation is waiting to start
  227. # or is already running, in which case we wait (or just
  228. # give up and return)
  229. if wait:
  230. while self.current_sync_operation is not None:
  231. self.condition.wait()
  232. else:
  233. if self.current_sync_operation is not None:
  234. return False
  235. self.async += 1
  236. finally:
  237. self.condition.release()
  238. if not wait:
  239. return True
  240. def do_release_read_lock(self):
  241. self.condition.acquire()
  242. try:
  243. self.async -= 1
  244. # check if we are the last asynchronous reader thread
  245. # out the door.
  246. if self.async == 0:
  247. # yes. so if a sync operation is waiting, notifyAll to wake
  248. # it up
  249. if self.current_sync_operation is not None:
  250. self.condition.notifyAll()
  251. elif self.async < 0:
  252. raise LockError("Synchronizer error - too many "
  253. "release_read_locks called")
  254. finally:
  255. self.condition.release()
  256. def do_acquire_write_lock(self, wait = True):
  257. self.condition.acquire()
  258. try:
  259. # here, we are not a synchronous reader, and after returning,
  260. # assuming waiting or immediate availability, we will be.
  261. if wait:
  262. # if another sync is working, wait
  263. while self.current_sync_operation is not None:
  264. self.condition.wait()
  265. else:
  266. # if another sync is working,
  267. # we dont want to wait, so forget it
  268. if self.current_sync_operation is not None:
  269. return False
  270. # establish ourselves as the current sync
  271. # this indicates to other read/write operations
  272. # that they should wait until this is None again
  273. self.current_sync_operation = _threading.currentThread()
  274. # now wait again for asyncs to finish
  275. if self.async > 0:
  276. if wait:
  277. # wait
  278. self.condition.wait()
  279. else:
  280. # we dont want to wait, so forget it
  281. self.current_sync_operation = None
  282. return False
  283. finally:
  284. self.condition.release()
  285. if not wait:
  286. return True
  287. def do_release_write_lock(self):
  288. self.condition.acquire()
  289. try:
  290. if self.current_sync_operation is not _threading.currentThread():
  291. raise LockError("Synchronizer error - current thread doesnt "
  292. "have the write lock")
  293. # reset the current sync operation so
  294. # another can get it
  295. self.current_sync_operation = None
  296. # tell everyone to get ready
  297. self.condition.notifyAll()
  298. finally:
  299. # everyone go !!
  300. self.condition.release()