Python 线程 运行() 阻塞
Python thread run() blocking
我试图创建一个可以被异常终止的线程 class(因为我试图让线程等待一个事件)当我创建以下内容时:
import sys
class testThread(threading.Thread):
def __init__(self):
super(testThread,self).__init__()
self.daemon = True
def run(self):
try:
print('Running')
while 1:
pass
except:
print('Being forced to exit')
test1 = testThread()
test2 = testThread()
print(test1.daemon)
test1.run()
test2.run()
sys.exit()
然而,运行程序只会打印出一条运行消息,直到另一条被终止。这是为什么?
问题是您正在调用 run
方法。
这只是您实现的一个普通的旧方法,它会执行您放入其主体中的任何操作。在这种情况下,正文是一个无限循环,因此调用 run
只会永远循环。
启动线程的方法是start
方法。这个方法是Thread
class的一部分,它的作用是:
Start the thread’s activity.
It must be called at most once per thread object. It arranges for the object’s run()
method to be invoked in a separate thread of control.
所以,如果你调用它,它会启动一个新线程,使新线程运行成为你的run()
方法,并立即return,这样主线程可以保持做其他事情。1这就是你想要的。
1.正如让-弗朗索瓦·法布尔 (Jean-François Fabre) 所指出的,您仍然不会在这里获得任何真正的并行性。忙循环在多线程代码中从来都不是一个好主意,如果你在 CPython 或 PyPy 中 运行 宁这个,几乎所有的忙循环都在执行 Python 字节码,同时持有GIL,并且一次只能有一个线程持有 GIL。因此,从粗略的角度来看,事情看起来是并发的——三个线程正在 运行ning,并且都在取得进展。但是如果你放大,两个线程同时进行的地方几乎没有重叠,通常甚至不足以弥补小的调度程序开销。
我试图创建一个可以被异常终止的线程 class(因为我试图让线程等待一个事件)当我创建以下内容时:
import sys
class testThread(threading.Thread):
def __init__(self):
super(testThread,self).__init__()
self.daemon = True
def run(self):
try:
print('Running')
while 1:
pass
except:
print('Being forced to exit')
test1 = testThread()
test2 = testThread()
print(test1.daemon)
test1.run()
test2.run()
sys.exit()
然而,运行程序只会打印出一条运行消息,直到另一条被终止。这是为什么?
问题是您正在调用 run
方法。
这只是您实现的一个普通的旧方法,它会执行您放入其主体中的任何操作。在这种情况下,正文是一个无限循环,因此调用 run
只会永远循环。
启动线程的方法是start
方法。这个方法是Thread
class的一部分,它的作用是:
Start the thread’s activity.
It must be called at most once per thread object. It arranges for the object’s
run()
method to be invoked in a separate thread of control.
所以,如果你调用它,它会启动一个新线程,使新线程运行成为你的run()
方法,并立即return,这样主线程可以保持做其他事情。1这就是你想要的。
1.正如让-弗朗索瓦·法布尔 (Jean-François Fabre) 所指出的,您仍然不会在这里获得任何真正的并行性。忙循环在多线程代码中从来都不是一个好主意,如果你在 CPython 或 PyPy 中 运行 宁这个,几乎所有的忙循环都在执行 Python 字节码,同时持有GIL,并且一次只能有一个线程持有 GIL。因此,从粗略的角度来看,事情看起来是并发的——三个线程正在 运行ning,并且都在取得进展。但是如果你放大,两个线程同时进行的地方几乎没有重叠,通常甚至不足以弥补小的调度程序开销。