Coverage for src/qollib/processing/thread.py: 91%

32 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-02 08:34 +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. 

5 

6@author: hoelken 

7""" 

8 

9import logging 

10 

11from concurrent.futures import Executor 

12 

13log = logging.getLogger() 

14 

15 

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 """ 

22 

23 def __init__(self, func: callable, args: object): 

24 self.function = func 

25 self.arguments = args 

26 self.future = None 

27 

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 

33 

34 def is_submitted(self) -> bool: 

35 return self.future is not None 

36 

37 def is_done(self) -> bool: 

38 return self.is_submitted() and self.future.done() 

39 

40 @property 

41 def exception(self): 

42 if not self.is_done(): 

43 return None 

44 return self.future.exception() 

45 

46 @property 

47 def result(self): 

48 if not self.is_submitted(): 

49 return None 

50 return self.future.result() 

51 

52 def cancel(self): 

53 try: 

54 self.future.cancel() 

55 except RuntimeError as e: 

56 log.warning('Unable to cancel thread: %s', e)