Multithreading

Alex Martelli aleax at aleax.it
Fri Jan 25 05:15:32 EST 2002


"Geiger Ho" <s997659 at ee.cuhk.edu.hk> wrote in message
news:Pine.GSO.4.05.10201251734280.4685-100000 at sparc41...
> Hi all,
>
>   I have a script below which intends to have output: 0, 1, 2, 3, 4.
> However what I get is 4, 4, 4, 4, 4. Why? How can I correct it?
>
> ------------------------------------------
> from threading import Thread
>
> class MyThread(Thread):
> def __init__(self, num_t):
> Thread.__init__(self)
> MyThread.num = num_t
> def run(self):
> print MyThread.num
>
> for i in range(5)
> x = MyThread(i)
> x.start()

The 'why' is because each of your threads is trying to set the
same, identical variable, shared among all threads -- MyThread.num,
a class-attribute thus shared by all instances.

Simplest way to correct it is do change the two uses of MyThread.num
to self.num in your definition of class MyThread.

Of course there is no guarantee whatsoever about the order in which
the various numbers will come out, but you will get some permutation
of range(5).


Alex






More information about the Python-list mailing list