简体   繁体   中英

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


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 ...

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. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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