如何从线程实例方法访问实例变量?

时间:2021-06-17 22:23:58

标签: python concurrency python-multithreading threadpoolexecutor concurrent.futures

我一直在努力弄清楚如何从运行在单独线程中的实例方法访问实例变量,如下例所示。我认为在 5 秒后从主线程调用 test.set_finished 方法后会跳过循环。

但是我的循环一直在计数,我不明白为什么。如果有人能帮我一点忙并告诉我我需要做什么不同的事情或者我正在尝试做的事情根本不可能,那就太好了。

import time
import concurrent.futures

class TestClass(object):

    def __init__(self):
        super(TestClass, self).__init__()
        self.finished = False

    def do_something(self):
        i = 0
        while not self.finished:
            i+=1
            print(i)
            time.sleep(1)

    def set_finished(self, finished_arg):
        self.finished = finished_arg

    def startThreadedMethod(self):
        with concurrent.futures.ThreadPoolExecutor() as executor:
            t1 = executor.submit(self.do_something)


test = TestClass()

test.startThreadedMethod()
time.sleep(5)
test.set_finished(True)

0 个答案:

没有答案
相关问题