我试图了解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
打印__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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句