Difficult-Rocket/Difficult_Rocket/utils/thread.py

59 lines
1.4 KiB
Python
Raw Normal View History

2021-09-08 23:38:34 +08:00
# -------------------------------
# Difficult Rocket
2022-06-27 16:51:14 +08:00
# Copyright © 2021-2022 by shenjackyuanjie 3695888@qq.com
2021-09-08 23:38:34 +08:00
# All rights reserved
# -------------------------------
"""
writen by shenjackyuanjie
mail: 3695888@qq.com
github: @shenjackyuanjie
gitee: @shenjackyuanjie
"""
import threading
2022-07-04 10:36:19 +08:00
from typing import Union
from threading import Lock
2022-09-04 13:02:58 +08:00
from Difficult_Rocket import DR_option, crash
2022-07-04 10:36:19 +08:00
from Difficult_Rocket.exception.threading import LockTimeOutError
2021-09-08 23:38:34 +08:00
class Threads(threading.Thread):
def run(self):
2022-09-04 13:02:58 +08:00
if DR_option.record_thread:
2021-09-09 23:54:03 +08:00
crash.all_thread.append(self)
super().run()
2022-07-04 10:36:19 +08:00
class ThreadLock:
def __init__(self, the_lock: Lock, time_out: Union[float, int] = 1 / 60) -> None:
2022-07-04 10:36:19 +08:00
self.lock = the_lock
2022-07-16 20:20:23 +08:00
self.time_out = time_out
2022-07-04 10:36:19 +08:00
2022-07-16 20:20:23 +08:00
def __enter__(self):
self.lock.acquire(timeout=self.time_out)
2022-07-04 10:36:19 +08:00
if not self.lock.locked():
2022-09-04 13:02:58 +08:00
raise LockTimeOutError(f'Lock time Out with {self.time_out}')
2022-07-16 20:20:23 +08:00
return self
2022-07-04 10:36:19 +08:00
def __exit__(self, exc_type, exc_val, exc_tb):
if self.lock.locked():
self.lock.release()
2022-07-04 10:36:19 +08:00
if __name__ == "__main__":
from Difficult_Rocket.exception import TestError
2022-07-04 10:36:19 +08:00
thread_lock = Lock()
test_lock = ThreadLock(thread_lock)
with test_lock:
print('do some thing')
2022-07-04 10:36:19 +08:00
...
with test_lock:
print('do some error')
raise TestError('ah lock test')