| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
import pytest |
| 6 |
import threading |
| 7 |
from typing import Any, Optional, Generic, TypeVar |
| 8 |
from scalene.scalene_sigqueue import ScaleneSigQueue |
| 9 |
import queue |
| 10 |
|
| 11 |
T = TypeVar("T") |
| 12 |
|
| 13 |
|
| 14 |
class TestScaleneSigQueue(Generic[T]): |
| 15 |
|
| 16 |
__test__ = False |
| 17 |
|
| 18 |
def __init__(self, process: Any) -> None: |
| 19 |
self.queue: queue.SimpleQueue[Optional[T]] = queue.SimpleQueue() |
| 20 |
self.process = process |
| 21 |
self.thread: Optional[threading.Thread] = None |
| 22 |
self.lock = threading.RLock() |
| 23 |
|
| 24 |
def put(self, item: Optional[T]) -> None: |
| 25 |
"""Add an item to the queue.""" |
| 26 |
self.queue.put(item) |
| 27 |
|
| 28 |
def get(self) -> Optional[T]: |
| 29 |
"""Get one item from the queue.""" |
| 30 |
return self.queue.get() |
| 31 |
|
| 32 |
def start(self) -> None: |
| 33 |
"""Start processing.""" |
| 34 |
|
| 35 |
if not self.thread: |
| 36 |
self.thread = threading.Thread(target=self.run, daemon=True) |
| 37 |
self.thread.start() |
| 38 |
|
| 39 |
def stop(self) -> None: |
| 40 |
"""Stop processing.""" |
| 41 |
if self.thread: |
| 42 |
self.queue.put(None) |
| 43 |
|
| 44 |
|
| 45 |
self.thread.join() |
| 46 |
self.thread = None |
| 47 |
|
| 48 |
def run(self) -> None: |
| 49 |
"""Run the function processing items until stop is called. |
| 50 |
|
| 51 |
Executed in a separate thread.""" |
| 52 |
while True: |
| 53 |
item = self.queue.get() |
| 54 |
if item is None: |
| 55 |
break |
| 56 |
with self.lock: |
| 57 |
self.process(*item) |
| 58 |
|
| 59 |
|
| 60 |
def test_scalene_sigqueue(): |
| 61 |
results = [] |
| 62 |
|
| 63 |
def process_function(*args): |
| 64 |
results.append(args) |
| 65 |
|
| 66 |
sigqueue = TestScaleneSigQueue(process_function) |
| 67 |
sigqueue.start() |
| 68 |
|
| 69 |
sigqueue.put((1, 2, 3)) |
| 70 |
sigqueue.put((4, 5, 6)) |
| 71 |
sigqueue.put(None) |
| 72 |
|
| 73 |
sigqueue.stop() |
| 74 |
|
| 75 |
assert results == [(1, 2, 3), (4, 5, 6)] |