-
Notifications
You must be signed in to change notification settings - Fork 1
/
concurrency.py
404 lines (321 loc) · 10.5 KB
/
concurrency.py
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
from collections import defaultdict, deque
from concurrent.futures import Executor
from datetime import datetime, timedelta
from heapq import heappop, heappush
from threading import Condition, Lock, Thread
class AtomicInc:
def __init__(self, value: int = 0):
self.value = value
self.lock = Lock()
self.cv = Condition(self.lock)
def inc_and_get(self, v: int) -> int:
with self.cv:
self.value += v
self.cv.notify_all()
return self.value
def set(self, v: int):
with self.cv:
self.value = v
self.cv.notify_all()
def wait_until_exceeds(self, v: int):
with self.cv:
self.cv.wait_for(lambda: self.value > v)
class CAS:
def __init__(self, value: any):
self.value = value
self.lock = Lock()
self.cv = Condition(self.lock)
def get(self) -> any:
with self.cv:
return self.value
def set(self, v: any):
with self.cv:
self.value = v
self.cv.notify_all()
def cas(self, prev_value: any, new_value: any) -> bool:
with self.cv:
if self.value == prev_value:
self.value = new_value
self.cv.notify_all()
return True
return False
class Barrier:
def __init__(self, max_arrivals: int):
self.max_arrivals = max_arrivals
self.arrivals = 0
self.lock = Lock()
self.cv = Condition(self.lock)
def arrive(self):
with self.cv:
self.arrivals += 1
self.cv.wait_for(lambda: self.arrivals >= self.max_arrivals)
self.cv.notify_all()
def wait(self):
with self.cv:
self.cv.wait_for(lambda: self.arrivals >= self.max_arrivals)
class AutoBarrier:
def __init__(self, max_arrivals: int):
self.max_arrivals = max_arrivals
self.arrivals = 0
self.lock = Lock()
self.cv = Condition(self.lock)
def arrive(self):
with self.cv:
self.arrivals += 1
max_arrivals = (
self.arrivals - self.arrivals % self.max_arrivals + self.max_arrivals
)
if self.arrivals == max_arrivals:
self.cv.notify_all()
else:
self.cv.wait_for(lambda: self.arrivals >= max_arrivals)
def wait(self):
with self.cv:
max_arrivals = (
self.arrivals - self.arrivals % self.max_arrivals + self.max_arrivals
)
self.cv.wait_for(lambda: self.arrivals >= max_arrivals)
class Event:
def __init__(self):
self.signaled = False
self.lock = Lock()
self.cv = Condition(self.lock)
def signal(self):
with self.cv:
self.signaled = True
self.cv.notify_all()
def wait(self):
with self.cv:
self.cv.wait_for(lambda: self.signaled)
def reset(self):
with self.cv:
self.signaled = False
class AutoEvent:
def __init__(self):
self.signaled = False
self.lock = Lock()
self.cv = Condition(self.lock)
def signal(self):
with self.cv:
self.signaled = True
self.cv.notify_all()
def wait(self):
with self.cv:
self.cv.wait_for(lambda: self.signaled)
self.signaled = False
class ConditionEvent:
def __init__(self):
self.signaled = 0
self.pendging = 0
self.lock = Lock()
self.cv = Condition(self.lock)
def signal(self):
with self.cv:
self.signaled += 1
self.cv.notify_all()
def signal_all(self):
with self.cv:
self.signaled = self.pending
self.cv.notify_all()
def wait(self):
with self.cv:
pid = self.pending
self.pendging += 1
self.cv.wait_for(lambda: self.signaled > pid)
class Semaphore:
def __init__(self, value: int):
self.value = value
self.lock = Lock()
self.cv = Condition(self.lock)
def release(self):
with self.cv:
self.value += 1
self.cv.notify_all()
def acquire(self):
with self.cv:
self.cv.wait_for(lambda: self.value > 0)
self.value -= 1
def try_acquire(self, timeout) -> bool:
with self.cv:
self.cv.wait_for(lambda: self.value > 0, timeout)
if self.value > 0:
self.value -= 1
return True
return False
class RWLock:
def __init__(self):
self.readers = 0
self.writers = 0
self.lock = Lock()
self.cv = Condition(self.lock)
def lock_read(self):
with self.cv:
self.cv.wait_for(lambda: self.writers <= 0)
self.readers += 1
self.cv.notify_all()
def unlock_read(self):
with self.cv:
self.readers -= 1
self.cv.notify_all()
def lock_write(self):
with self.cv:
self.cv.wait_for(lambda: self.writers + self.readers == 0)
self.writers += 1
self.cv.notify_all()
def unlock_write(self):
with self.cv:
self.writers -= 1
self.cv.notify_all()
class RWLock2:
def __init__(self):
self.readers = 0
self.writers = 0
self.pending_writers = 0
self.lock = Lock()
self.cv = Condition(self.lock)
def lock_read(self):
with self.cv:
self.cv.wait_for(lambda: self.writers + self.pending_writers <= 0)
self.readers += 1
self.cv.notify_all()
def unlock_read(self):
with self.cv:
self.readers -= 1
self.cv.notify_all()
def lock_write(self):
with self.cv:
self.pending_writers += 1
self.cv.wait_for(lambda: self.writers + self.pending_writers <= 0)
self.pending_writers -= 1
self.writers += 1
self.cv.notify_all()
def unlock_write(self):
with self.cv:
self.writers -= 1
self.cv.notify_all()
class UnboundedBlockingQueue:
def __init__(self):
self.queue = deque()
self.lock = Lock()
self.cv = Condition(self.lock)
def enqueue(self, item: any):
with self.cv:
self.queue.append(item)
self.cv.notify_all()
def dequeue(self) -> any:
with self.cv:
self.cv.wait_for(lambda: bool(self.queue))
return self.queue.popleft()
class BlockingQueue:
def __init__(self, capacity: int):
self.capacity = capacity
self.queue = deque()
self.lock = Lock()
self.cv = Condition(self.lock)
def enqueue(self, item: any):
with self.cv:
self.cv.wait_for(lambda: len(self.queue) < self.capacity)
self.queue.append(item)
self.cv.notify_all()
def dequeue(self) -> any:
with self.cv:
self.cv.wait_for(lambda: bool(self.queue))
return self.queue.popleft()
class DelayQueue:
def __init__(self):
self.entries: list[tuple[datetime, any]] = []
self.lock = Lock()
self.cv = Condition(self.lock)
def enqueue(self, value: any, timeout: timedelta):
with self.cv:
heappush(self.entries, (datetime.now() + timeout, value))
self.cv.notify_all()
def dequeue(self) -> any:
with self.cv:
while not self.entries or self.entries[0][0] > datetime.now():
if not self.entries:
self.cv.wait()
else:
self.cv.wait((self.entries[0][0] - datetime.now()).total_seconds())
return heappop(self.entries)[1]
class DelayExecutor:
def __init__(self, exec: Executor):
self.exec = exec
self.runnables = DelayQueue()
self.worker = Thread(target=self.run)
self.worker.start()
def run(self):
while True:
runnable = self.runnables.dequeue()
self.exec.submit(runnable)
def execute(self, runnable, timeout=timedelta(seconds=0)):
if timeout == timedelta(seconds=0):
self.exec.submit(runnable)
else:
self.runnables.enqueue(runnable, timeout)
class ExpireMap:
def __init__(self):
self.table = defaultdict(lambda: {"value": None, "when": None})
self.keys = DelayQueue()
self.worker = Thread(target=self._run_worker)
self.worker.start()
self.lock = Lock()
def _run_worker(self):
while True:
key = self.keys.dequeue()
with self.lock:
if key in self.table:
when = self.table[key]["when"]
if when is None or when <= datetime.now():
del self.table[key]
def contains(self, key):
with self.lock:
return key in self.table
def get(self, key):
with self.lock:
return self.table[key]["value"]
def put(self, key, value):
with self.lock:
self.table[key]["value"] = value
def remove(self, key, timeout=0):
with self.lock:
if timeout > 0:
when = datetime.now() + timedelta(seconds=timeout)
self.table[key]["when"] = when
else:
del self.table[key]
if timeout > 0:
self.keys.enqueue(key, timeout)
class ExpireMap:
def __init__(self):
self.table = defaultdict(lambda: {"value": None, "when": None})
self.keys = DelayQueue()
self.worker = Thread(target=self._run_worker)
self.worker.start()
self.lock = Lock()
def _run_worker(self):
while True:
key = self.keys.dequeue()
with self.lock:
if key in self.table:
when = self.table[key]["when"]
if when is None or when <= datetime.now():
del self.table[key]
def contains(self, key):
with self.lock:
return key in self.table
def get(self, key):
with self.lock:
return self.table[key]["value"]
def put(self, key, value):
with self.lock:
self.table[key]["value"] = value
def remove(self, key, timeout=0):
with self.lock:
if timeout > 0:
when = datetime.now() + timedelta(seconds=timeout)
self.table[key]["when"] = when
else:
del self.table[key]
if timeout > 0:
self.keys.enqueue(key, timeout)