I am trying to understand Threads in Python.
The code
And now I have a problem, which I have surrounded in one simple class:
# -*- 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()
Description
Here is what the class does : The class has two attributes :
__idwhich is an identifier for the object, given when the constructor is called__propertyThatShouldNotBeSharedis a list and will contain a text value
Now the methods
run()contains an infinite loop in which I calldummy1()and thendummy2()dummy1()which adds to attribute (list)__propertyThatShouldNotBeSharedthe value "Test value" only IF the__idof the object is equal to 2dummy2()checks if the size of the list__propertyThatShouldNotBeSharedis strictly superior to 0, then- for each value in
__propertyThatShouldNotBeSharedit prints the id of - the object and the value contained in
__propertyThatShouldNotBeShared - then it removes the value
- for each value in
Here is the output that I get when I launch the program :
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
The problem
As you can see in the first line of the output I get this "1"...which means that, at some point, the object with the id "1" tries to print something on the screen...and actually it does! But this should be impossible! Only object with id "2" should be able to print anything!
What is the problem in this code ? Or what is the problem with my logic?