简体   繁体   English

Python线程run()阻塞

[英]Python thread run() blocking

I was attempting to create a thread class that could be terminated by an exception (since I am trying to have the thread wait on an event) when I created the following: 当我创建以下代码时,我试图创建一个可能被异常终止的线程类(因为我试图让线程等待一个事件):

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

However, running the program will only print out one Running message, until the other is terminated. 但是,运行该程序只会打印出一条“正在运行”消息,直到另一条消息终止。 Why is that? 这是为什么?

The problem is that you're calling the run method. 问题在于您正在调用run方法。

This is just a plain old method that you implement, which does whatever you put in its body. 这只是您实现的一个普通的旧方法,它可以执行您在其主体中所做的任何事情。 In this case, the body is an infinite loop, so calling run just loops forever. 在这种情况下,主体是一个无限循环,因此调用run永远都是循环。

The way to start a thread is the start method. 启动线程的方法是start方法。 This method is part of the Thread class, and what it does is: 此方法是Thread类的一部分,它的作用是:

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()方法。

So, if you call this, it will start a new thread, make that new thread run your run() method, and return immediately, so the main thread can keep doing other stuff. 因此,如果调用此方法,它将启动一个新线程,使该新线程运行run()方法,然后立即返回,以便主线程可以继续执行其他操作。 1 That's what you want here. 1这就是您想要的。


1. As pointed out by Jean-François Fabre, you're still not going to get any real parallelism here. 1.正如让·弗朗索瓦·法布尔(Jean-FrançoisFabre)所指出的那样,您仍然不会在这里得到任何真正的并行性。 Busy loops are never a great idea in multithreaded code, and if you're running this in CPython or PyPy, almost all of that busy looping is executing Python bytecode while holding the GIL, and only one thread can hold the GIL at a time. 繁忙的循环从来都不是多线程代码中的好主意,如果您在CPython或PyPy中运行它,几乎所有繁忙的循环都在保持GIL的同时执行Python字节码,并且一次只能有一个线程保持GIL。 So, from a coarse view, things look concurrent—three threads are running, and all making progress. 因此,从粗略的角度看,事情看起来是并发的,三个线程正在运行,所有线程都在进步。 But if you zoom in, there's almost no overlap where two threads progress at once, usually not even enough to make up for the small scheduler overhead. 但是,如果放大,则几乎没有重叠,两个线程同时进行,通常甚至不足以弥补小的调度程序开销。

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

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