gpt4 book ai didi

python - 使用线程时访问父类(super class)变量

转载 作者:行者123 更新时间:2023-12-01 09:21:47 24 4
gpt4 key购买 nike

我有一个带有线程列表的类,这些线程需要访问父类(super class)中的变量。我不确定如何以安全的方式访问该变量以便线程执行其操作。

我想要做什么的想法。

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

最佳答案

在您的特定示例中,您想要:

  1. 将父级传递给子级,以便他们知道应该向谁求助
  2. 使用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()

关于python - 使用线程时访问父类(super class)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50753603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com