examples for ch.20: Concurrency Models

This commit is contained in:
Luciano Ramalho
2021-01-20 22:32:36 -03:00
parent bf4a2be8b9
commit ff436f9ef8
7 changed files with 308 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
from time import perf_counter
from typing import Tuple, List, NamedTuple
from threading import Thread
from queue import SimpleQueue
from primes import is_prime, NUMBERS
class Result(NamedTuple): # <3>
flag: bool
elapsed: float
JobQueue = SimpleQueue[Tuple[int, Result]] # <4>
def check(n: int) -> Result: # <5>
t0 = perf_counter()
res = is_prime(n)
return Result(res, perf_counter() - t0)
def job(n: int, results: JobQueue) -> None: # <6>
results.put((n, check(n))) # <7>
def main() -> None:
t0 = perf_counter()
results: JobQueue = SimpleQueue() # <1>
workers: List[Thread] = [] # <2>
for n in NUMBERS:
worker = Thread(target=job, args=(n, results)) # <3>
worker.start() # <4>
workers.append(worker) # <5>
for _ in workers: # <6>
n, (prime, elapsed) = results.get() # <7>
label = 'P' if prime else ' '
print(f'{n:16} {label} {elapsed:9.6f}s')
time = perf_counter() - t0
print('Total time:', f'{time:0.2f}s')
if __name__ == '__main__':
main()