MrJ*_*y42 3 python multithreading class list object
我试图理解Python中的Threads.
代码
现在我遇到了一个问题,我在一个简单的课程中包含了这个问题:
# -*- 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()
Run Code Online (Sandbox Code Playgroud)
描述
这是类的作用:该类有两个属性:
__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
Run Code Online (Sandbox Code Playgroud)
问题
正如您在输出的第一行中看到的那样,我得到了这个"1"......这意味着,在某些时候,ID为"1"的对象会尝试在屏幕上打印某些内容......实际上它确实如此!但这应该是不可能的!只有id为"2"的对象才能打印任何东西!
这段代码有什么问题?或者我的逻辑有什么问题?
问题是这样的:
class myClassWithThread(threading.Thread):
__propertyThatShouldNotBeShared = []
Run Code Online (Sandbox Code Playgroud)
它为共享的所有对象定义了一个列表.你应该做这个:
class myClassWithThread(threading.Thread):
def __init__(self, id):
self.__propertyThatShouldNotBeShared = []
# the other code goes here
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1643 次 |
| 最近记录: |