为什么 python 线程模块中所有线程的名称都相同?
why is name of all threads same in python threading module?
from threading import *
def myfunc(i,name):
print("This is " + str(name))
for i in range(4):
name = current_thread().name
t = Thread(target=myfunc, args=(i,name,))
t.start()
current_thread().getName()
也给出相同的 results.I 想知道它是这样工作的还是 运行 同一个线程,所以它传递了名称 MainThread
?
输出:
这是 MainThread
这是 MainThread
这是 MainThread
这是 MainThread
current_thread()
总是 returns 调用 current_thread()
的线程。您重复检索正在执行循环的线程的名称,而不是该线程启动的任何线程的名称。
如果您想获得在循环中启动的线程的名称,您可以让 它们 调用 current_thread()
:
import threading
def target():
print("This is", threading.current_thread().name)
for i in range(4):
Thread(target=target).start()
from threading import *
def myfunc(i,name):
print("This is " + str(name))
for i in range(4):
name = current_thread().name
t = Thread(target=myfunc, args=(i,name,))
t.start()
current_thread().getName()
也给出相同的 results.I 想知道它是这样工作的还是 运行 同一个线程,所以它传递了名称 MainThread
?
输出:
这是 MainThread
这是 MainThread
这是 MainThread
这是 MainThread
current_thread()
总是 returns 调用 current_thread()
的线程。您重复检索正在执行循环的线程的名称,而不是该线程启动的任何线程的名称。
如果您想获得在循环中启动的线程的名称,您可以让 它们 调用 current_thread()
:
import threading
def target():
print("This is", threading.current_thread().name)
for i in range(4):
Thread(target=target).start()