Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can two infinite loops be ran at once?

Tags:

python

loops

I want to be able to have two while Trueloops running at the same time. Would this be possible?

I am extremely new to Python, so I do not know how to get round this problem.

This is the code I made:

import time

def infiniteLoop():
    while True:
        print('Loop 1')
        time.sleep(1)

infiniteLoop()

while True:
    print('Loop 2')
    time.sleep(1)

Right now, it just prints a 'Loop 1'

Thanks in advance

like image 507
RobCoder102 Avatar asked Sep 16 '25 00:09

RobCoder102


2 Answers

To run both loops at once, you either need to use two threads or interleave the loops together.

Method 1:

import time
def infiniteloop():
    while True:
        print('Loop 1')
        time.sleep(1)
        print('Loop 2')
        time.sleep(1)

infiniteloop()

Method 2:

import threading
import time

def infiniteloop1():
    while True:
        print('Loop 1')
        time.sleep(1)

def infiniteloop2():
    while True:
        print('Loop 2')
        time.sleep(1)

thread1 = threading.Thread(target=infiniteloop1)
thread1.start()

thread2 = threading.Thread(target=infiniteloop2)
thread2.start()
like image 198
Brian Avatar answered Sep 17 '25 14:09

Brian


While Brian's answer has you covered, Python's generator functions (and the magic of yield) allow for a solution with two actual loops and without threads:

def a():
    while True:  # infinite loop nr. 1 (kind of)
        print('Loop 1')
        yield

def b():
    for _ in a():    # infinite loop nr. 2
        print('Loop 2')

> b()
Loop 1
Loop 2
Loop 1
Loop 2
....

Here, the two loops in a() and b() are truly interleaved in the sense that in each iteration, execution is passed back and forth between the two.

like image 41
user2390182 Avatar answered Sep 17 '25 15:09

user2390182