仅在最后一次执行完成后才从循环中执行函数
我有一个循环(所有这些都是在 Python 3.10 中完成的),与需要消耗循环数据的函数相比,它的运行速度相对较快。我不想减慢数据速度,并试图找到一种异步运行该函数的方法,但仅在完成后再次执行该函数...基本上:
queue=[]
def flow():
thing=queue[0]
time.sleep(.5)
print(str(thing))
delete=queue.pop(0)
p1 = multiprocessing.Process(target=flow)
while True:
print('stream')
time.sleep(.25)
if len(queue)<1:
print('emptyQ')
queue.append('flow')
p1.start()
我尝试在线程和进程中运行该函数似乎尝试在该功能仍在运行时启动另一个。我厌倦了使用队列来传递数据并作为信号量,直到函数结束时才删除项目,并且仅添加项目并在队列为空时启动线程或进程,但这似乎也不起作用。
编辑:添加一个明确的问题... 有没有办法异步执行一个函数而不需要同时多次执行它?
编辑2:使用功能测试代码进行更新(准确地重现失败),因为真实的代码更加实质性......我注意到它似乎在函数的第一次执行时起作用(打印在函数内部不起作用...... .) 但下一次执行无论出于何种原因都会失败。我认为加载该进程两次会很累吗?
我得到的错误是 - RuntimeError:在当前进程完成其引导阶段之前尝试启动新进程...
I have a loop (all this is being done in Python 3.10) that is running relatively fast compared to a function that needs to consume data from the loop. I don't want to slow down the data and am trying to find a way to run the function asynchronously but only execute the function again after completion... basically:
queue=[]
def flow():
thing=queue[0]
time.sleep(.5)
print(str(thing))
delete=queue.pop(0)
p1 = multiprocessing.Process(target=flow)
while True:
print('stream')
time.sleep(.25)
if len(queue)<1:
print('emptyQ')
queue.append('flow')
p1.start()
I've tried running the function in a thread and a process and both seem to try to start another while the function is still running. I tired using a queue to pass the data and as a semaphore by not removing the item until the end of the function and only adding an item and starting the thread or process if the queue was empty, but that didn't seem to work either.
EDIT : to add an explicit question...
Is there a way to execute a function asynchronously without executing it multiple time simultaneously?
EDIT2 : Updated with functional test code (accurately reproduces failure) since real code is a bit more substantial... I have noticed that it seems to work on the first execution of the function (the print doesn't work inside the function...) but the next execution it fails for whatever reason. I assume it tires to load the process twice?
The error I get is - RuntimeError : An attempt has been made to start a new process before the current process has finished its bootstrapping phase...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论