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):
|
2021-09-22 06:21:48 +08:00
|
|
|
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)
|
2021-09-22 06:21:48 +08:00
|
|
|
super().run()
|
2022-07-04 10:36:19 +08:00
|
|
|
|
|
|
|
|
|
|
|
class ThreadLock:
|
|
|
|
|
2022-09-03 22:35:57 +08:00
|
|
|
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):
|
2022-09-03 22:35:57 +08:00
|
|
|
# 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():
|
2022-09-03 22:35:57 +08:00
|
|
|
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):
|
2022-09-04 01:26:20 +08:00
|
|
|
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
|
2022-09-03 22:35:57 +08:00
|
|
|
# print('exit with no error')
|
2022-07-04 10:36:19 +08:00
|
|
|
return None
|
|
|
|
else:
|
|
|
|
# 出 bug 了
|
2022-09-03 22:35:57 +08:00
|
|
|
# print(f'exit with error {exc_type} {exc_val}')
|
2022-07-04 10:36:19 +08:00
|
|
|
return None
|
|
|
|
|
2022-09-03 22:35:57 +08:00
|
|
|
# def __del__(self):
|
|
|
|
# print('del me!')
|
|
|
|
# self.__del__()
|
|
|
|
|
2022-07-04 10:36:19 +08:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2022-09-03 22:35:57 +08:00
|
|
|
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:
|
2022-09-03 22:35:57 +08:00
|
|
|
print('do some thing')
|
2022-07-04 10:36:19 +08:00
|
|
|
...
|
2022-09-03 22:35:57 +08:00
|
|
|
with test_lock:
|
|
|
|
print('do some error')
|
|
|
|
raise TestError('ah lock test')
|