[英]Are these threads running in parallel
我有以下代码:
from threading import Thread
from threading import currentThread
def f(i, name="default"):
print("Thread named {} with id={} is working".format(name, i))
for i in range(3):
Thread(target=f, args=(i,), kwargs={"name": "%s" % currentThread().getName()}).start()
这是我得到的结果:
>> Thread named MainThread with id=0 is working
>> Thread named MainThread with id=1 is working
>> Thread named MainThread with id=2 is working
如果这三个线程并行运行,为什么它们都具有相同的名称,如果它们不是并行运行,我该如何更改我的代码以使它们并行运行?
参数kwargs={"name": "%s" % currentThread().getName()}
的值在调用Thread
的同时(或更准确地说,就在之前)进行评估。 因此,每个线程都会将关键字参数name="MainThread"
传递给它应该执行的 function。
尝试在f
中调用currentThread()
,例如:
def f(i):
print("Thread named {} with id={} is working".format(currentThread().getName(), i)
如果这三个线程并行运行为什么它们都具有相同的名称
这是因为您的currentThread().getName()
正在产生它们的线程中被调用,因此它将该线程的名称传递给所有产生的线程。
如果它们没有并行运行,我该如何更改我的代码以使它们并行运行?
它们在不同的线程中运行,但由于 CPython 的行为,它们在同一处理器上运行 Python 字节码,因此不完全并发。 为了使它们在单独的处理器上运行,请使用Multiprocessing
模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.