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-07-16 20:20:23 +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):
|
|
|
|
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 (exc_type is None) and (exc_val is None) and (exc_tb is None):
|
|
|
|
# 没有出 bug
|
|
|
|
self.lock.release()
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
# 出 bug 了
|
|
|
|
self.lock.release()
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
|
|
thread_lock = Lock()
|
|
|
|
|
|
|
|
test_lock = ThreadLock(thread_lock)
|
|
|
|
|
|
|
|
with test_lock:
|
|
|
|
...
|
|
|
|
|