Can two infinite loops be ran at once?

前提是你 提交于 2021-01-18 06:45:11

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/36847817/can-two-infinite-loops-be-ran-at-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!