Thread in Python : class attribute (list) not thread-safe?

Viewed 3215

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 :

  • __id which is an identifier for the object, given when the constructor is called
  • __propertyThatShouldNotBeShared is a list and will contain a text value

Now the methods

  • run() contains an infinite loop in which I call dummy1() and then dummy2()
  • dummy1() which adds to attribute (list) __propertyThatShouldNotBeShared the value "Test value" only IF the __id of the object is equal to 2
  • dummy2() checks if the size of the list __propertyThatShouldNotBeShared is strictly superior to 0, then
    • for each value in __propertyThatShouldNotBeShared it prints the id of
    • the object and the value contained in __propertyThatShouldNotBeShared
    • then it removes the value

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?

3 Answers
Related