gpt4 book ai didi

python - 线程即将终止怎么办?

转载 作者:行者123 更新时间:2023-11-28 22:58:01 24 4
gpt4 key购买 nike

我有一个正在运行的线程即将终止,但此时,我已经想摆脱它的引用。我可以直接开始并期待最好的结果,还是应该以某种特殊方式处理它?<​​/p>

class CoolThing(object):

def __init__(self):
self.thread = None

def run_in_background(self, callback, period=0.5):
if self.thread:
raise RuntimeError

def worker():
worker.running = True
while worker.running:
if some_event():
callback(self)
time.sleep(period)

self.thread = (threading.Thread(target=worker), worker)
self.thread[0].start()

def stop_background(self, join=False):
if not self.thread:
raise RuntimeError

# Make the worker function end harmfully.
self.thread[1].running = False

if join:
self.thread[0].join()

# What should I now do with the thread being about to
# terminate, when not being joined?

# ...

self.thread = None

最佳答案

当离开 while 循环时,您应该在从 worker 中调用的回调中将线程设置为 None:

修改:现在还支持立即重启后台进程

import time
import threading

class CoolThing(object):

def __init__(self):
self.thread = None

def run_in_background(self, callback, period=0.5):
wait_count = 0
while True:
if self.thread:
if self.thread[1].running or wait_count>10:
raise RuntimeError()
time.sleep(0.5)
wait_count += 1
else:
break

def worker():
t0 = time.time()
worker.running = True
while worker.running:
if time.time()-t0>2:
callback()
t0 = time.time()
time.sleep(period)
worker.callback()

worker.callback = self.dispose
self.thread = (threading.Thread(target=worker), worker)
self.thread[0].start()

def stop_background(self, join=False):
if not self.thread:
raise RuntimeError
self.thread[1].running = False
if join:
self.thread[0].join()
self.stopping = True

def dispose(self):
self.thread = None
self.stopping

def my_callback():
print "Beep"

if __name__=="__main__":
cool_thing = CoolThing()
cool_thing.run_in_background(my_callback, 0.5)
time.sleep(10)
cool_thing.stop_background()
# Immediatley restart process
cool_thing.run_in_background(my_callback, 0.5)
time.sleep(10)
cool_thing.stop_background()
print cool_thing.thread
time.sleep(3)
print cool_thing.thread

给出输出:

Beep
Beep
Beep
(<Thread(Thread-2, started 10760)>, <function worker at 0x02DEDD70>)
None

所以在调用 stop_background 之后,self.thread 仍然设置,但稍后,它是 None。您还可以保存 worker.callback 变量并按其名称调用 dispose(),但这样,代码更加灵活。

编辑 2:新要求、新代码示例

我为 worker (SRP) 创建了一个单独的类,CoolThing 保存了此类 worker 的列表。如果 run_background(...) 启动,它会检查是否有任何工作人员仍在运行(没有停止请求),然后引发 RuntimeError。否则,启动一个新的 worker 。stop_background() 告诉每个 worker 停止,每个 worker 调用一个回调,然后从所有 worker 列表中删除这个 worker。

import time
import threading

class Worker(threading.Thread):
def __init__(self, callback, period=0.5, finished_callback = None):
threading.Thread.__init__(self)
self.callback = callback
self.period = period
self._stop_requested = False
self._finished_callback = finished_callback

def run(self):
t0 = time.time()
while not self._stop_requested:
if time.time()-t0>2:
self.callback()
t0 = time.time()
time.sleep(self.period)
if self._finished_callback:
self._finished_callback(self)

def request_stop(self):
self._stop_requested = True

@property
def stopping(self):
return self._stop_requested

class CoolThing(object):

def __init__(self):
self.workers = []
self.workers_lock = threading.Lock()

def run_in_background(self, callback, period=0.5):
if len([w for w in self.workers if not w.stopping])>0:
raise RuntimeError()
worker = Worker(callback, period, finished_callback=self.dispose)
with self.workers_lock:
self.workers.append(worker)
worker.start()

def stop_background(self, join=False):
if len(self.workers) == 0:
raise RuntimeError()
for worker in self.workers:
worker.request_stop()
if join:
for worker in self.workers:
worker.join()

def dispose(self, worker):
with self.workers_lock:
self.workers.remove(worker)

def my_callback():
print "Beep"

if __name__=="__main__":
cool_thing = CoolThing()
cool_thing.run_in_background(my_callback, 0.5)
time.sleep(10)
print cool_thing.workers
cool_thing.stop_background()
# Immediatley restart process
cool_thing.run_in_background(my_callback, 0.5)
print cool_thing.workers
time.sleep(5)
print cool_thing.workers
time.sleep(5)
cool_thing.stop_background()
print cool_thing.workers
time.sleep(3)
print cool_thing.workers

关于python - 线程即将终止怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14215047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com