Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

RWLock.py 2.0 KB

You have to be logged in to leave a comment. Sign In
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
  1. import multiprocessing
  2. class RWLock():
  3. """
  4. Multiprocessing non-recursive reader-writer lock
  5. """
  6. def __init__(self):
  7. self._a = multiprocessing.RawArray('I', 2)
  8. #_a[0] : readers counter
  9. #_a[1] : writer flag
  10. self._v = memoryview(self._a).cast('B').cast('I')
  11. self._l = multiprocessing.Lock()
  12. def read_lock(self):
  13. v = self._v
  14. l = self._l
  15. while True:
  16. # Non blocky wait writer flag release
  17. while v[1] != 0:
  18. pass
  19. l.acquire()
  20. if v[1] != 0:
  21. # Writer flag is still acquired, go to non-blocky waiting
  22. l.release()
  23. continue
  24. # Inc readers counter
  25. v[0] += 1
  26. l.release()
  27. return
  28. def read_unlock(self):
  29. v = self._v
  30. l = self._l
  31. l.acquire()
  32. c = v[0]
  33. if c == 0:
  34. raise Exception('Invalid lock state')
  35. # Dec readers counter
  36. v[0] = c-1
  37. l.release()
  38. def write_lock(self):
  39. v = self._v
  40. l = self._l
  41. while True:
  42. # Non blocky wait writer flag release
  43. while v[1] != 0:
  44. pass
  45. l.acquire()
  46. if v[1] != 0:
  47. # Writer flag is still acquired, go to non-blocky waiting
  48. l.release()
  49. continue
  50. # set writer flag
  51. v[1] = 1
  52. l.release()
  53. # Wait all readers gone
  54. while v[0] != 0:
  55. pass
  56. return
  57. def write_unlock(self):
  58. v = self._v
  59. c = v[1]
  60. if c == 0:
  61. raise Exception('Invalid lock state')
  62. # Remove writer flag
  63. v[1] = 0
  64. def __getstate__(self):
  65. d = self.__dict__.copy()
  66. # pop unpicklable memoryview object
  67. d.pop('_v')
  68. return d
  69. def __setstate__(self, d):
  70. # restore memoryview of RawArray
  71. d['_v'] = memoryview(d['_a']).cast('B').cast('I')
  72. self.__dict__.update(d)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...