Coverage for src/qollib/processing/thread.py: 90%
31 statements
« prev ^ index » next coverage.py v7.5.4, created at 2024-06-24 08:41 +0000
« prev ^ index » next coverage.py v7.5.4, created at 2024-06-24 08:41 +0000
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4The threads hold information on the function (and result) to execute in a thread or process.
6@author: hoelken
7"""
9import logging
11from concurrent.futures import Executor
13log = logging.getLogger()
16class Thread:
17 """
18 # Thread
19 The threads hold information on the function to execute in a thread or process.
20 Provides an interface to the `future` object once submitted to an executer.
21 """
23 def __init__(self, func: callable, args: object):
24 self.function = func
25 self.arguments = args
26 self.future = None
28 def submit(self, executor: Executor):
29 """Start execution via executor"""
30 if not self.is_submitted():
31 self.future = executor.submit(self.function, self.arguments)
32 return self
34 def is_submitted(self) -> bool:
35 return self.future is not None
37 def is_done(self) -> bool:
38 return self.is_submitted() and self.future.done()
40 @property
41 def exception(self):
42 if not self.is_done():
43 return None
44 return self.future.exception()
46 @property
47 def result(self):
48 if not self.is_submitted():
49 return None
50 return self.future.result()
52 def cancel(self):
53 try:
54 self.future.cancel()
55 except RuntimeError as e:
56 log.warning('Unable to cancel thread: %s', e)