简体   繁体   English

这些线程是否并行运行

[英]Are these threads running in parallel

I have the following code:我有以下代码:

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

This is the result that I get:这是我得到的结果:

>> Thread named MainThread with id=0 is working
>> Thread named MainThread with id=1 is working
>> Thread named MainThread with id=2 is working

if these three threads are running in parallel why they all have the same name, if they are not running in parallel how can I change my code to make them run in parallel?如果这三个线程并行运行,为什么它们都具有相同的名称,如果它们不是并行运行,我该如何更改我的代码以使它们并行运行?

The value of the argument kwargs={"name": "%s" % currentThread().getName()} is evaluated at the same time as (or more precisely, just before) Thread is called.参数kwargs={"name": "%s" % currentThread().getName()}的值在调用Thread的同时(或更准确地说,就在之前)进行评估。 So each thread gets the keyword argument name="MainThread" passed to the function it is supposed to execute.因此,每个线程都会将关键字参数name="MainThread"传递给它应该执行的 function。

Try calling currentThread() inside f , for example:尝试在f中调用currentThread() ,例如:

def f(i):
    print("Thread named {} with id={} is working".format(currentThread().getName(), i)

if these three threads are running in parallel why they all have the same name如果这三个线程并行运行为什么它们都具有相同的名称

This is because your currentThread().getName() is being called in the thread spawning them, so it is passing the name of that thread to all the spawned ones.这是因为您的currentThread().getName()正在产生它们的线程中被调用,因此它将该线程的名称传递给所有产生的线程。

if they are not running in parallel how can I change my code to make them run in parallel?如果它们没有并行运行,我该如何更改我的代码以使它们并行运行?

They are running in separate threads, but due to the behaviour of CPython, they are running the Python bytecode on the same processor, thus not fully concurrently.它们在不同的线程中运行,但由于 CPython 的行为,它们在同一处理器上运行 Python 字节码,因此不完全并发。 In order to make them run on separate processors, use the Multiprocessing module.为了使它们在单独的处理器上运行,请使用Multiprocessing模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM