简体   繁体   English

是否可以在 python 中同时运行两个无限循环

[英]Is it possible to run a two infinite while loops at the same time in python

I have made a timer while loop using我在循环使用时制作了一个计时器

   while True:
       time.sleep(1)
       timeClock += 1

is it possible to execute this loop while executing another infinite while loop at the same time in the same program because I have made a command to show the elapsed time whenever I want The whole Code is是否有可能在同一个程序中同时执行另一个无限 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

Thanks in advance提前致谢

You can do a very similar thing with multiprocessing ...你可以用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)

Multiprocessing has more overhead than multithreading, but it can often make better use of your machine's capabilities as it is truly running two or more processes in parallel.多处理比多线程有更多的开销,但它通常可以更好地利用您的机器的功能,因为它真正并行运行两个或多个进程。 Python's multithreading really doesn't, due to the dreaded GIL.由于可怕的 GIL,Python 的多线程实际上没有。 To understand that, check this out要了解这一点, 请检查一下

If you want multiple loops running at the same time, you should use multi-threading.如果你想同时运行多个循环,你应该使用多线程。 This can be done using the threading library as shown below:这可以使用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

If the only purpose is a clock however, you'd be better off following kaya's advice and using the time library itself.但是,如果唯一的目的是时钟,那么您最好听从 kaya 的建议并使用时间库本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM