gpt4 book ai didi

python - Python 中的线程 : class attribute (list) not thread-safe?

转载 作者:太空宇宙 更新时间:2023-11-03 13:01:06 24 4
gpt4 key购买 nike

我正在尝试理解 Python 中的线程。

代码

现在我遇到了一个问题,我在一个简单的类中解决了这个问题:

# -*- coding: utf-8 -*-
import threading

class myClassWithThread(threading.Thread):

__propertyThatShouldNotBeShared = []
__id = None
def __init__(self, id):
threading.Thread.__init__(self)
self.__id = id

def run(self):
while 1:
self.dummy1()
self.dummy2()

def dummy1(self):
if self.__id == 2:
self.__propertyThatShouldNotBeShared.append("Test value")


def dummy2(self):
for data in self.__propertyThatShouldNotBeShared:
print self.__id
print data
self.__propertyThatShouldNotBeShared.remove(data)



obj1 = myClassWithThread(1)
obj2 = myClassWithThread(2)
obj3 = myClassWithThread(3)

obj1.start()
obj2.start()
obj3.start()

描述

这是类的作用:该类有两个属性:

  • __id 这是对象的标识符,在调用构造函数时给出
  • __propertyThatShouldNotBeShared 是一个列表,将包含一个文本值

现在是方法

  • run() 包含一个无限循环,我在其中调用了 dummy1(),然后是 dummy2()
  • dummy1() 添加到属性(列表)__propertyThatShouldNotBeShared 值“测试值”仅当对象的 __id 相等时到 2
  • dummy2() 检查列表 __propertyThatShouldNotBeShared 的大小是否严格优于 0,然后
    • 对于 __propertyThatShouldNotBeShared 中的每个值,它打印 id
    • __propertyThatShouldNotBeShared中包含的对象和值
    • 然后删除该值

这是我启动程序时得到的输出:

21

Test valueTest value

2
Test value
Exception in thread Thread-2:
Traceback (most recent call last):
File "E:\PROG\myFace\python\lib\threading.py", line 808, in __bootstrap_inner
self.run()
File "E:\PROG\myFace\myProject\ghos2\src\Tests\threadDeMerde.py", line 15, in run
self.dummy2()
File "E:\PROG\myFace\myProject\ghos2\src\Tests\threadDeMerde.py", line 27, in dummy2
self.__propertyThatShouldNotBeShared.remove(data)
ValueError: list.remove(x): x not in list

问题

正如您在输出的第一行中看到的,我得到了这个“1”...这意味着,在某个时候,id 为“1”的对象试图在屏幕上打印一些东西...并且实际上它确实如此!但这应该是不可能的!只有 ID 为“2”的对象才能打印任何内容!

这段代码有什么问题?或者我的逻辑有什么问题?

最佳答案

问题是这样的:

class myClassWithThread(threading.Thread):
__propertyThatShouldNotBeShared = []

它为所有共享的对象定义了一个列表。你应该这样做:

class myClassWithThread(threading.Thread):
def __init__(self, id):
self.__propertyThatShouldNotBeShared = []
# the other code goes here

关于python - Python 中的线程 : class attribute (list) not thread-safe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20847062/

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