threaded_lambda.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #
  2. # Copyright (c) Contributors to the Open 3D Engine Project.
  3. # For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. #
  5. # SPDX-License-Identifier: Apache-2.0 OR MIT
  6. #
  7. import threading
  8. class ThreadedLambda:
  9. """
  10. A base class that encapsulates a long operation
  11. via a lambda function that runs on a thread. Typically
  12. the long operation is a subprocess or a series of subprocesses.
  13. """
  14. def __init__(self, basic_description: str, job_func):
  15. """
  16. @param job_func The function that will do the work. It should check the state of
  17. self._is_cancelled and other member variables and cancel pending work
  18. if needed.
  19. """
  20. self._basic_description = basic_description
  21. self._is_finished = False
  22. self._is_success = False
  23. # The job_func should check for the status of this variable and exit immediately if needed.
  24. self._is_cancelled = False
  25. # Subclasses should store here the result of stdout+stderr.
  26. self._report_msg = ""
  27. self._thread = threading.Thread(target=job_func)
  28. def start(self):
  29. """
  30. Do not override.
  31. """
  32. self._thread.start()
  33. def is_finished(self) -> bool:
  34. return self._is_finished
  35. def is_success(self) -> bool:
  36. return self._is_success
  37. def cancel(self):
  38. if self._is_cancelled:
  39. print(f"Job <{self._basic_description}> is already cancelled!")
  40. return
  41. self._is_cancelled = True
  42. self._cancel_internal()
  43. self._thread.join()
  44. def get_report_msg(self) -> str:
  45. return self._report_msg
  46. def get_basic_description(self) -> str:
  47. return self._basic_description
  48. def _cancel_internal(self):
  49. """
  50. A protected method that gives the chance to the subclass
  51. to do something when the operation is being cancelled.
  52. """
  53. pass
  54. # class ThreadedLambda END
  55. ######################################################