![](/img/trans.png)
[英]Is there a way to run two loops (for loops ,while loops,....) in the same time?
[英]How To Run 2 While Loops At The Same Time
当我运行它,我只看到打印的“用户移动”而不是时钟,我需要他们同时工作,因为他们有不同的等待时间。 第一个 function 每秒等待,第二个 function 等待 3.5 秒。
import time
import multiprocessing
def get_timer(t):
mins = t // 60
hours = 0
if mins > 59:
hours = int((mins / 60))
mins = int(mins % 60)
secs = int(t % 60)
clock = '{:02d}:{:02d}:{:02d}'.format(hours, mins, secs)
return clock
def set_clock(start_time, t):
while (time.time() - start_time) < t:
print("----")
clock = get_timer(int(round(t - (time.time() - start_time), 0)))
print(clock)
print("----")
time.sleep(0.99)
else:
print(f'Finished')
return
def move_user(start_time, t):
while (time.time() - start_time) < t:
print('User Moved')
time.sleep(0.35)
else:
print(f'Finished')
return
times = int(input("Enter The Number Of Times: "))
start = time.time()
p1 = multiprocessing.Process(target=move_user, args=(start, times))
p2 = multiprocessing.Process(target=set_clock, args=(start, times))
if __name__ == '__main__':
p2.start()
p1.start()
p2.join()
p1.join()
您可以使用asyncio.gather
同时运行两个 while 循环
import asyncio
async def set_clock(start_time, t):
#other stuff
print('---')
await asyncio.sleep(0.99)
async def move_user(start_time, t):
while (time.time() - start_time) < t:
print('User Moved')
await asyncio.sleep(0.35)
else:
print(f'Finished')
return
if __name__ == '__main__':
asyncio.run(asyncio.gather(move_user(start_time, t), set_clock(start_time, t))
# or in a async function
await asyncio.gather(move_user(start_time, t), set_clock(start_time, t)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.