Python中线程间共享对象

2024-03-29 07:08:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中使用线程时遇到了一些问题

我需要的是:

线程1

  • 启动线程2,给它“data”对象作为参数
  • 做些工作
  • 停止线程2
  • 检查结果

线程2

  • 读取循环中线程1的数据

我大致实现了

class ReaderThread(threading.Thread)
    def __init__(self, data):
        super().__init__()
        self.data = data
        self.exit = False

    def run(self):
        while not self.exit:
            somehow modify self.data

    def stop(self):
        self.exit = True
        self.join()

主线程创建一个ReaderThread实例并调用start(),几秒钟后调用stop()

class MainThread():
    def __init__(self):
        self.data = set()
        self.thread = ReaderThread(self.data)

    def function(self):
        self.thread.start()
        whoptydoo
        self.thread.stop()

问题是,thread1并没有真正修改thread2的“exit”变量,thread2(ReaderThread)也没有修改thread1的“data”。因此,这里显然存在一些内存共享问题

我的想法是“这是所有的指针”,这似乎并不正确。 请问正确的方法是什么


Tags: 对象selfdata参数initdefexit线程
2条回答

您的RenderThread类似乎不完整(缺少:Thread初始化)。 一旦完成,您的示例似乎会按预期工作

编辑问题中的示例更改后,仍然有效

#!/usr/bin/env python

import time
import threading

class ReaderThread(threading.Thread):
    def __init__(self, data):
        super().__init__()
        self.data = data
        self.exit = False

    def run(self):
        t0=time.time()
        while not self.exit:
            # somehow modify self.data
            time.sleep(0.25)
            self.data.add(int(100.0*(time.time()-t0)))

    def stop(self):
        self.exit = True
        self.join()

class MainThread():
    def __init__(self):
        self.data = set()
        self.thread = ReaderThread(self.data)

    def function(self):
        self.thread.start()
        time.sleep(2) # whoptydoo
        self.thread.stop()

mt=MainThread()
mt.function()
print(mt.data) # {225, 100, 200, 75, 175, 50, 150, 25, 125}

这里是交易:在ReaderThread处有data字段,在MainThread处有data字段。当在ReaderThread中执行此self.data = smth时,可以为ReaderThread字段设置此值,但从不访问MainThread的任何属性。这两个实例具有相似的命名字段,但它们不相同

要实现您想要的,您应该从ReaderThread.run返回一个值,或者将MainThread实例传递给ReaderThread以便能够修改它。看起来选项2更适合你

class ReaderThread(threading.Thread)
    def __init__(self, main_instance):
        self.main = main_instance
        self.exit = False

    def run(self):
        while not self.exit:
            self.main.data = whatever

    def stop(self):
        self.exit = True
        self.join()

class MainThread():
    def __init__(self):
        self.data = set()
        self.thread = ReaderThread(self)

    def function(self):
        self.thread.start()
        whoptydoo
        self.thread.stop()

顺便说一句,仔细看之后,我对你做错了什么有了另一个想法。由于MainThread.data是一个set(),因此是可变的-您的代码将按原样工作,但前提是您准确地修改{},而不是重新分配它(我怀疑您本可以这样做)

相关问题 更多 >