RobCoder102
RobCoder102

Reputation: 43

Can two infinite loops be ran at once?

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

Upvotes: 4

Views: 22853

Answers (2)

Brian
Brian

Reputation: 1667

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()

Upvotes: 16

user2390182
user2390182

Reputation: 73490

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.

Upvotes: 2

Related Questions