在python中可以同时运行两个无限while循环吗

2024-06-26 18:01:32 发布

您现在位置: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

提前谢谢


Tags: 代码命令程序truefortimedef时间
2条回答

你可以用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的多线程真的没有。要理解这一点,check this out

如果希望同时运行多个循环,则应使用多线程。这可以使用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

然而,如果唯一的目的是一个时钟,你最好听从卡娅的建议,使用时间库本身

相关问题 更多 >