简体   繁体   English

python中的非阻塞类(独立线程)

[英]Non-blocking class in python (detached Thread)

I'm trying to create a kind of non-blocking class in python, but I'm not sure how. 我正在尝试在python中创建一种非阻塞类,但不确定如何。

I'd like a class to be a thread itself, detached from the main thread so other threads can interact with it. 我希望一个类本身就是一个线程,与主线程分离,以便其他线程可以与之交互。

In a little example: 在一个小例子中:

#!/usr/bin/python2.4

import threading
import time

class Sample(threading.Thread):
    def __init__(self):
        super(Sample, self).__init__()
        self.status = 1
        self.stop = False

    def run(self):
        while not(self.stop):
            pass

    def getStatus(self):
        return self.status

    def setStatus(self, status):
        self.status = status

    def test(self):
        while self.status != 0:
            time.sleep(2)

#main
sample = Sample()
sample.start()
sample.test()
sample.setStatus(0)
sample.stop()

What I'd like is having the "sample" instance running as a separate thread (detached from the main one) so, in the example, when the main thread reaches sample.test(), sample (and only "sample") would go to sleep for 2 seconds. 我想要的是让“示例”实例作为单独的线程运行(与主线程分离),因此,在示例中,当主线程到达sample.test()时,示例(仅“示例”)将睡2秒钟 In the meanwhile, the main thread would continue its execution and set sample's status to 0. When after the 2 seconds "sample" wakes up it would see the status=0 and exit the while loop. 同时,主线程将继续执行并将样品的状态设置为0。在2秒钟后,“样品”被唤醒时,它将看到状态= 0并退出while循环。

The problem is that if I do this, the line sample.setStatus(0) is never reached (creating an infinite loop). 问题是,如果执行此操作,将永远无法到达sample.setStatus(0)行(创建无限循环)。 I have named the threads, and it turns out that by doing this, test() is run by the main thread. 我已经命名了线程,事实证明,通过这样做,test()由主线程运行。

I guess I don't get the threading in python that well... 我想我没有很好地了解python中的线程...

Thank you in advance 先感谢您

The object's run() method is what executes in a separate thread. 对象的run()方法是在单独的线程中执行的。 When you call sample.test(), that executes in the main thread, so you get your infinite loop. 当您调用sample.test()时,它将在主线程中执行,因此您将遇到无限循环。

Perhaps something like this? 也许像这样?

import threading
import time

class Sample(threading.Thread):
    def __init__(self):
        super(Sample, self).__init__()
        self.stop = False

    def run(self):
        while not(self.stop):
            print('hi')
            time.sleep(.1)

    def test(self):
        print('testing...')
        time.sleep(2)

#main
sample = Sample()
sample.start()      # Initiates second thread which calls sample.run()
sample.test()       # Main thread calls sample.test
sample.stop=True    # Main thread sets sample.stop
sample.join()       # Main thread waits for second thread to finish

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

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