2021-09-08 23:38:34 +08:00
|
|
|
# -------------------------------
|
|
|
|
# Difficult Rocket
|
2023-01-20 14:08:12 +08:00
|
|
|
# Copyright © 2020-2023 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):
|
2021-09-22 06:21:48 +08:00
|
|
|
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)
|
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):
|
|
|
|
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):
|
2022-09-04 01:26:20 +08:00
|
|
|
if self.lock.locked():
|
|
|
|
self.lock.release()
|
2022-09-03 22:35:57 +08:00
|
|
|
|
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')
|