Difficult-Rocket/Difficult_Rocket/utils/thread.py

72 lines
1.7 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
2021-09-08 23:38:34 +08:00
from Difficult_Rocket import 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):
2021-09-08 23:38:34 +08:00
if crash.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):
# print('enter!')
2022-07-16 20:20:23 +08:00
self.lock.acquire(timeout=self.time_out)
2022-07-04 10:36:19 +08:00
if not self.lock.locked():
raise LockTimeOutError('')
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 (exc_type is None) and (exc_val is None) and (exc_tb is None):
# 没有出 bug
# print('exit with no error')
2022-07-04 10:36:19 +08:00
return None
else:
# 出 bug 了
# print(f'exit with error {exc_type} {exc_val}')
2022-07-04 10:36:19 +08:00
return None
# def __del__(self):
# print('del me!')
# self.__del__()
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')