forked from cool-RR/python_toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_write_lock.py
More file actions
53 lines (37 loc) · 1.48 KB
/
read_write_lock.py
File metadata and controls
53 lines (37 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''
See documentation of class `ReadWriteLock` defined in this module.
'''
# todo: organize.
from python_toolbox import context_management
from . import original_read_write_lock
__all__ = ['ReadWriteLock']
class ContextManager(context_management.ContextManager):
def __init__(self, lock, acquire_func):
self.lock = lock
self.acquire_func = acquire_func
def __enter__(self):
self.acquire_func()
return self.lock
def __exit__(self, exc_type, exc_value, exc_traceback):
self.lock.release()
class ReadWriteLock(original_read_write_lock.ReadWriteLock):
'''
A ReadWriteLock subclassed from a different ReadWriteLock class defined
in the module original_read_write_lock.py, (See the documentation of the
original class for more details.)
This subclass adds two context managers, one for reading and one for
writing.
Usage:
read_write_lock = ReadWriteLock()
with read_write_lock.read:
pass # perform read operations here
with read_write_lock.write:
pass # perform write operations here
'''
# todo: rename from acquireRead style to acquire_read style
def __init__(self, *args, **kwargs):
original_read_write_lock.ReadWriteLock.__init__(self, *args, **kwargs)
self.read = ContextManager(self, self.acquireRead)
self.write = ContextManager(self, self.acquireWrite)