clearml-server/apiserver/utilities/threads_manager.py

57 lines
1.8 KiB
Python
Raw Normal View History

2019-07-08 21:04:26 +00:00
from functools import wraps
from threading import Lock, Thread
2021-01-05 14:58:57 +00:00
from typing import ClassVar, Callable
2019-07-08 21:04:26 +00:00
class ThreadsManager:
objects = {}
lock = Lock()
2021-01-05 14:58:57 +00:00
request_context_creator: ClassVar[Callable] = None
terminating: ClassVar[bool] = False
2019-07-08 21:04:26 +00:00
2019-12-14 21:35:18 +00:00
def __init__(self, name=None, **threads):
self.name = name or self.__class__.__name__
2019-12-14 21:35:18 +00:00
self.objects = {}
self.lock = Lock()
2019-12-14 21:52:39 +00:00
for thread_name, thread in threads.items():
2019-12-14 21:35:18 +00:00
if issubclass(thread, Thread):
thread = thread()
thread.start()
elif isinstance(thread, Thread):
if not thread.is_alive():
thread.start()
else:
2019-12-14 21:52:39 +00:00
raise Exception(f"Expected thread or thread class ({thread_name}): {thread}")
2019-12-14 21:35:18 +00:00
2019-12-14 21:52:39 +00:00
self.objects[thread_name] = thread
2019-12-14 21:35:18 +00:00
2019-07-08 21:04:26 +00:00
def register(self, thread_name, daemon=True):
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
with self.lock:
thread = self.objects.get(thread_name)
if not thread:
thread = Thread(
2019-12-14 21:35:18 +00:00
target=f, name=f"{self.name}_{thread_name}", args=args, kwargs=kwargs
2019-07-08 21:04:26 +00:00
)
thread.daemon = daemon
thread.start()
self.objects[thread_name] = thread
return thread.ident
return wrapper
return decorator
2019-12-14 21:35:18 +00:00
def __getattr__(self, item):
if item in self.objects:
return self.objects[item]
return self.__getattribute__(item)
def __getitem__(self, item):
if item in self.objects:
return self.objects[item]
raise KeyError(item)