|
4 | 4 | import queue
|
5 | 5 | from collections.abc import Callable
|
6 | 6 | from threading import Thread
|
7 |
| -from typing import TYPE_CHECKING, Any |
| 7 | +from typing import Any |
8 | 8 |
|
9 |
| -from resonate.models.commands import Command, Return |
10 |
| -from resonate.models.result import Ko, Ok |
| 9 | +from resonate.models.result import Ko, Ok, Result |
11 | 10 | from resonate.utils import exit_on_exception
|
12 | 11 |
|
13 |
| -if TYPE_CHECKING: |
14 |
| - from concurrent.futures import Future |
15 |
| - |
16 | 12 |
|
17 | 13 | class Processor:
|
18 |
| - def __init__(self, cq: queue.Queue[Command | tuple[Command, Future] | None]) -> None: |
| 14 | + def __init__(self) -> None: |
19 | 15 | self.threads = set[Thread]()
|
20 | 16 | for _ in range(min(32, (os.cpu_count() or 1))):
|
21 | 17 | self.threads.add(Thread(target=self._run, daemon=True))
|
22 | 18 |
|
23 |
| - self.sq = queue.Queue[tuple[str, str, Callable[[], Any]] | None]() |
24 |
| - self.cq = cq |
| 19 | + self.sq = queue.Queue[tuple[Callable[[], Any], Callable[[Result[Any]], None]]]() |
25 | 20 |
|
26 | 21 | @exit_on_exception
|
27 | 22 | def _run(self) -> None:
|
28 |
| - while sqe := self.sq.get(): |
29 |
| - id, cid, func = sqe |
| 23 | + while True: |
| 24 | + try: |
| 25 | + func, callback = self.sq.get() |
| 26 | + except queue.ShutDown: |
| 27 | + break |
| 28 | + |
30 | 29 | try:
|
31 | 30 | r = Ok(func())
|
32 | 31 | except Exception as e:
|
33 | 32 | r = Ko(e)
|
34 |
| - self.cq.put_nowait(Return(id, cid, r)) |
35 |
| - self.sq.task_done() |
36 | 33 |
|
37 |
| - self.sq.put(None) |
| 34 | + callback(r) |
| 35 | + self.sq.task_done() |
38 | 36 |
|
39 |
| - def enqueue(self, id: str, cid: str, func: Callable[[], Any]) -> None: |
40 |
| - self.sq.put((id, cid, func)) |
| 37 | + def enqueue(self, func: Callable[[], Any], callback: Callable[[Result[Any]], None]) -> None: |
| 38 | + self.sq.put((func, callback)) |
41 | 39 |
|
42 | 40 | def start(self) -> None:
|
43 | 41 | for t in self.threads:
|
44 | 42 | if not t.is_alive():
|
45 | 43 | t.start()
|
46 | 44 |
|
47 | 45 | def stop(self) -> None:
|
48 |
| - self.sq.put(None) |
| 46 | + self.sq.shutdown() |
49 | 47 | for t in self.threads:
|
50 | 48 | t.join()
|
| 49 | + self.sq.join() |
0 commit comments