【发布时间】:2018-03-21 13:39:31
【问题描述】:
我有一个多线程 Python 程序(金融交易),其中某些线程执行关键部分(例如在执行交易的过程中)。执行临界区的线程是守护线程。程序的主线程捕获SIGINT 并尝试通过释放子线程持有的所有资源来优雅地退出程序。为了防止主线程导致子线程突然终止;主线程将遍历子线程对象列表并调用它们的shutdown() 函数。此函数将阻塞,直到线程的关键部分完成后才返回。
以下是基本实现
class ChildDaemonThread(Thread):
def __init__(self):
self._critical_section = False
# other initialisations
def shutdown(self):
# called by parent thread before calling sys.exit(0)
while True:
if not self._critical_section:
break
# add code to prevent entering critical section
# do resource deallocation
def do_critical_stuff(self):
self._critical_section = True
# do critical stuff
self._critical_section = False
def run(self):
while True:
self._do_critical_stuff()
我不确定我的实现是否会起作用,因为当ChildDaemonThread 通过do_critical_stuff() 执行临界区时,如果父线程调用子线程的shutdown(),它会阻塞直到临界区执行,那么此时同时调用ChildDaemonThreadrun()和do_critical_stuff()这两个方法(我不确定这是否合法)。这可能吗?我的实现是否正确?有没有更好的方法来实现这一点?
【问题讨论】:
标签: python multithreading critical-section