Praful Malik
Praful Malik

Reputation: 11

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

Upvotes: 1

Views: 980

Answers (2)

CryptoFool
CryptoFool

Reputation: 23119

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

Upvotes: 4

Green-Avocado
Green-Avocado

Reputation: 891

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.

Upvotes: 3

Related Questions