-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_thread_loop.py
56 lines (41 loc) · 1.39 KB
/
main_thread_loop.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
import threading
from dataclasses import dataclass, field
from queue import PriorityQueue
from typing import Callable
import inject
from utils import show_exceptions
@dataclass(order=True)
class Callback:
func: Callable = field(compare=False)
priority: int = 10
def is_main_thread():
return threading.current_thread() == threading.main_thread()
class MainExecutor:
def __init__(self):
self.callbacks: PriorityQueue[Callback] = PriorityQueue()
self._alive = True
async def run_loop(self):
if not is_main_thread():
raise RuntimeError()
while self._alive:
with show_exceptions():
callback = self.callbacks.get()
callback.func()
def send_callback(self, callback: Callback):
self.callbacks.put_nowait(callback)
def close(self):
self._alive = False
def execute_in_main_thread(priority: int = 10):
def _decorator(func):
def _wrapper(*args, **kwargs):
if is_main_thread():
# Note that if thread is not main
# Then return value is None
return func(*args, **kwargs)
inject.instance(MainExecutor).send_callback(Callback(
(lambda: func(*args, **kwargs))
if args or kwargs else func,
priority
))
return _wrapper
return _decorator