| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import threading |
| 4 |
import time |
| 5 |
from typing import Any, List |
| 6 |
from unittest import TestCase |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
from pyinstrument.low_level.stat_profile import setstatprofile |
| 11 |
|
| 12 |
from ..util import busy_wait, do_nothing |
| 13 |
|
| 14 |
|
| 15 |
class CallCounter: |
| 16 |
def __init__(self, thread) -> None: |
| 17 |
self.thread = thread |
| 18 |
self.count = 0 |
| 19 |
|
| 20 |
def __call__(self, *args: Any, **kwds: Any) -> Any: |
| 21 |
assert self.thread is threading.current_thread() |
| 22 |
self.count += 1 |
| 23 |
|
| 24 |
|
| 25 |
def test_threaded(): |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
counters: list[CallCounter | None] = [None for _ in range(10)] |
| 30 |
stop = False |
| 31 |
|
| 32 |
def profile_a_busy_wait(i): |
| 33 |
thread = threads[i] |
| 34 |
counter = CallCounter(thread) |
| 35 |
counters[i] = counter |
| 36 |
|
| 37 |
setstatprofile(counter, 0.001) |
| 38 |
while not stop: |
| 39 |
do_nothing() |
| 40 |
setstatprofile(None) |
| 41 |
|
| 42 |
threads = [threading.Thread(target=profile_a_busy_wait, args=(i,)) for i in range(10)] |
| 43 |
for thread in threads: |
| 44 |
thread.start() |
| 45 |
|
| 46 |
while not stop: |
| 47 |
stop = all(c is not None and c.count > 10 for c in counters) |
| 48 |
|
| 49 |
for thread in threads: |
| 50 |
thread.join() |