当python中的过程中使用循环时,流程与执行
我尝试使用多处理在Python中运行以下代码结构。我在过程目标中使用循环时,以便该过程定期独立执行代码。但是,似乎没有并行执行过程,而是串行执行。当我删除WARE循环时,处理过程正常。 我试图搜索类似的问题,发现没有具体的答案,
import multiprocessing
import datetime, time
def f1():
while True:
print('F1 Cyclic : ', datetime.datetime.now())
time.sleep(1)
def f2():
while True:
print('F2 Cyclic : ', datetime.datetime.now())
time.sleep(2)
print('Starting main')
f1Process = multiprocessing.Process(target=f1())
f2Process = multiprocessing.Process(target=f2())
f1Process.daemon = False
f2Process.daemon = False
f1Process.start()
f2Process.start()
# f1Process.join()
# f2Process.join()
print('Ending main')
我的结果看起来像这样的
主
f1循环:2022-06-20 16:08:14.912327
f1 f1 cyclicclic:2022-06-06-20 16:08:08:15.928739
f1 f1循环:2022-06-20 16:08:16.935977
F1循环:2022-06-20 16:08:08:17.946611
f1循环:2022-06-06-20 16:08:
18.955279 19.959641
F1循环:2022-06-20 16:08:20.960894
F1循环:2022-06-20 16:08:21.971137
I am trying to run following code structure in python using multiprocessing. I am using while loop inside the process target so that the process is independently executing code periodically.However, it seems that processes are not getting executed parallel, rather serial execution happening. When i remove the while loop then processes works fine.
I tried to search for similar questions, and found that there was no concrete answer
import multiprocessing
import datetime, time
def f1():
while True:
print('F1 Cyclic : ', datetime.datetime.now())
time.sleep(1)
def f2():
while True:
print('F2 Cyclic : ', datetime.datetime.now())
time.sleep(2)
print('Starting main')
f1Process = multiprocessing.Process(target=f1())
f2Process = multiprocessing.Process(target=f2())
f1Process.daemon = False
f2Process.daemon = False
f1Process.start()
f2Process.start()
# f1Process.join()
# f2Process.join()
print('Ending main')
My result looks like this
Starting main
F1 Cyclic : 2022-06-20 16:08:14.912327
F1 Cyclic : 2022-06-20 16:08:15.928739
F1 Cyclic : 2022-06-20 16:08:16.935977
F1 Cyclic : 2022-06-20 16:08:17.946611
F1 Cyclic : 2022-06-20 16:08:18.955279
F1 Cyclic : 2022-06-20 16:08:19.959641
F1 Cyclic : 2022-06-20 16:08:20.960894
F1 Cyclic : 2022-06-20 16:08:21.971137
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于这2行而出现问题,因此将目标设置为
f1()
/f2()
正在执行该行中的功能(调用F1()时):分配目标以下以解决问题:
正确的工作代码应为:
The issue arises because of these 2 lines, setting the target as
f1()
/f2()
is executing the function in that line therefore, it gets stuck in infinite while loop(when f1() is called):Assign target as below to fix the issue:
The correct working code should be: