Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在处理线程时访问超类变量_Python_Multithreading_Python 3.x_Class - Fatal编程技术网

Python 在处理线程时访问超类变量

Python 在处理线程时访问超类变量,python,multithreading,python-3.x,class,Python,Multithreading,Python 3.x,Class,我有一个包含线程列表的类,这些线程需要访问超类中的变量。我不知道如何以安全的方式访问该变量,以便线程执行它们的任务 一个关于我要做什么的想法 from threading import Thread class Parent(): def __init__(self, num): self.num = num self.arr = [] def run(self): self.arr.append(Child(25))

我有一个包含线程列表的类,这些线程需要访问超类中的变量。我不知道如何以安全的方式访问该变量,以便线程执行它们的任务

一个关于我要做什么的想法

from threading import Thread


class Parent():

    def __init__(self, num):
        self.num = num
        self.arr = []

    def run(self):
        self.arr.append(Child(25))
        self.arr.append(Child(50))
        for child in a.arr:
            child.start()
        for child in a.arr:
            child.join()
        print(self.num)


class Child(Thread, Parent):

    def __init__(self, sum):
        Thread.__init__(self)
        self.sum = sum

    def run(self):
        # every thread should a.num + self.sum so I end up with a.num = 175
        pass


a = Parent(100)
a.run()

在您的特定示例中,您希望:

  • 把父母传给孩子,让他们知道应该向谁求助
  • 使用
    Lock
    同步关键部分(添加)
  • 像这样:

    from threading import Thread, Lock
    
    class Parent:
    
        def __init__(self, num):
            self.num = num
            self.arr = []
            self.lock = Lock()  # Create the Lock
    
        def run(self):
            self.arr.append(Child(25, self))  # pass parent to children
            self.arr.append(Child(50, self))  # 
            for child in a.arr:
                child.start()
            for child in a.arr:
                child.join()
            print(self.num)
    
    class Child(Thread, Parent):
    
        def __init__(self, sum_, parent):
            Thread.__init__(self)
            self.sum_ = sum_
            self.parent = parent
    
        def run(self):
            with self.parent.lock:  # this with section will be synchronized
                                    # against parent's lock
                self.parent.num += self.sum_
    
    a = Parent(100)
    a.run()