调度太多的小线程是个问题吗



调度太多从不重叠的小线程有问题吗?

例如,在python:中,应该从这样的东西中预期什么"意外"行为

from threading import Timer
def print_num_thread(wait_for=0.1, num_thread=0):
t = Timer(0.1, print_num_thread, [wait_for, num_thread+1])
# do something really quick (do << wait_for) like:
print(f'thread number {num_thread}')
t.start()
print_num_thread()

与相比,这有什么优势

from time import sleep
def print_num_while(wait_for=0.1, num_while=0):
while True:
# do something really quick like:
print(f'loop_number {num_while}')
num_while += 1
sleep(wait_for)
print_num_while()

如果使用一些资源,在第一种情况下停止线程而不设置t.daemon = True怎么样?

在没有如果使用某些资源,则设置t.daemon=True?

如果将t.daemon设置为True,线程将不会停止,而是成为一个守护进程。这意味着它应该在程序终止时继续运行。您可以使用thread.kill终止/停止线程。比较:在python repl中创建一个魔鬼线程,创建一个无线程,退出python repl,检查正在运行的进程。

与类似的东西相比,这有什么优势:
...

第一个例子不会阻塞线程,而第二个例子会。

要进行比较,请尝试:

print_num_thread()
print("I GOT HERE")

vs:

print_num_while()
print("I GOT HERE")

最新更新