[英]Is it possible to run a two infinite while loops at the same time in python
我在循环使用时制作了一个计时器
while True:
time.sleep(1)
timeClock += 1
是否有可能在同一个程序中同时执行另一个无限 while 循环的同时执行此循环,因为我已经创建了一个命令来随时显示经过的时间整个代码是
def clock():
while True:
time.sleep(1)
t += 1
print(t)
clock()
while True:
userInput = input("Do you want to know the total time this porgram has been running?\n Y for yes, N for no : ")
if userInput == Y:
print(t)
else:
pass
提前致谢
你可以用multiprocessing做非常相似的事情......
from multiprocessing import Process, Value
import time
def clock(t):
while True:
time.sleep(1)
t.value += 1
t = Value('i', 0)
p = Process(target=clock, args=[t])
p.start()
while True:
userInput = input("Do you want to know the total time this porgram has been running?\n Y for yes, N for no : ")
if userInput == 'Y':
print(t.value)
多处理比多线程有更多的开销,但它通常可以更好地利用您的机器的功能,因为它真正并行运行两个或多个进程。 由于可怕的 GIL,Python 的多线程实际上没有。 要了解这一点, 请检查一下
如果你想同时运行多个循环,你应该使用多线程。 这可以使用threading
库来完成,如下所示:
import threading
import time
def clock():
global t
while True:
time.sleep(1)
t += 1
print(t)
x = threading.Thread(target=clock)
x.start()
t = 0
while True:
userInput = input("Do you want to know the total time this porgram has been running?\n Y for yes, N for no : ")
if userInput == 'Y':
print(t)
else:
pass
但是,如果唯一的目的是时钟,那么您最好听从 kaya 的建议并使用时间库本身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.