在python中运行 2无限循环的正确方法吗?
Is it the right way to run 2 infiniteloop in python?
我在 python 中写了一个代码,其中包含 2 个无限循环,如下所示:
import threading
import time
ticker = 0
def ticking():
global ticker
while True:
time.sleep(1)
ticker +=1
print("ticker = {}".format(ticker))
def main_line():
while True:
print("Hello world")
time.sleep(4)
t1 = threading.Thread(target = ticking)
t2 = threading.Thread(target = main_line)
t1.start()
t2.start()
#t1.join()
if __name__ == "__main__":
t1.join()
#t2.join()
如果我不加入任何线程,它就不起作用,但是当我加入一个线程时,另一个线程也可以工作,但我不知道为什么?
谁能帮我解释一下?
这是因为你还“启动”了另一个线程。如果您对 t2.start()
发表评论,则该线程仅在 t1
.
上工作
t1.start()
# t2.start()
Join 用于阻塞调用方法,直到线程结束、抛出异常或超时。
join([timeout]) Wait until the thread terminates. This blocks the
calling thread until the thread whose join() method is called
terminates – either normally or through an unhandled exception – or
until the optional timeout occurs.
在你的例子中,你已经启动了两个线程。所以两个线程都在工作。但是一旦你用 t1.join() 阻塞了主线程,两个 运行 线程都将可见。
我在 python 中写了一个代码,其中包含 2 个无限循环,如下所示:
import threading
import time
ticker = 0
def ticking():
global ticker
while True:
time.sleep(1)
ticker +=1
print("ticker = {}".format(ticker))
def main_line():
while True:
print("Hello world")
time.sleep(4)
t1 = threading.Thread(target = ticking)
t2 = threading.Thread(target = main_line)
t1.start()
t2.start()
#t1.join()
if __name__ == "__main__":
t1.join()
#t2.join()
如果我不加入任何线程,它就不起作用,但是当我加入一个线程时,另一个线程也可以工作,但我不知道为什么? 谁能帮我解释一下?
这是因为你还“启动”了另一个线程。如果您对 t2.start()
发表评论,则该线程仅在 t1
.
t1.start()
# t2.start()
Join 用于阻塞调用方法,直到线程结束、抛出异常或超时。
join([timeout]) Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.
在你的例子中,你已经启动了两个线程。所以两个线程都在工作。但是一旦你用 t1.join() 阻塞了主线程,两个 运行 线程都将可见。