promlems with threading and print

Andreas Grommek andi at mozarellasalat.homelinux.net
Wed Jul 15 04:24:22 EDT 2009


Hi Newsgroup,

I'm new to python and I am familiarizing myself with threads (haven't done any threading in any
other language before...). I was playing around and discovered some weird behavior. Here is my code:

import threading
from time import sleep
from random import random
import sys

class MyThread(threading.Thread):

    def __init__(self, t, s):
        self.threadmarker = t
        self.sleeptime = s
        threading.Thread.__init__(self)

    def run(self):
        print("Tread", self.threadmarker, "is going to sleep for a while...")
        sys.stdout.flush()     #flush I/O
        sleep(self.sleeptime)  #go to sleep
        print("Tread", self.threadmarker, "is waking up and terminating")

a = 1
b = 20
for n in range(a, b):
   x = MyThread(n,random()*10.0)
   x.start()


This should create some threads which print messages, go to sleep for a random amount of time (max
10 seconds) and return with a message. When I run the code I get something like this (always different):

Tread 1 is going to sleep for a while...
Tread 2 is going to sleep for a while...
Tread 3 is going to sleep for a while...
Tread 4 is going to sleep for a while...
Tread 5 is going to sleep for a while...
Tread 6 is going to sleep for a while...
Tread 6 is going to sleep for a while...
Tread 7 is going to sleep for a while...
Tread 7 is going to sleep for a while...
Tread 7 is going to sleep for a while...
Tread 8 is going to sleep for a while...
(...)

Some "going to sleep" messages appear more than once. If I increase the number of thread the problem
gets worse and threads are even started out of order (but this alone would not worry me...).

Are some threads startet more than once or is this an issue with print? What else can I do in
addition to sys.stdout.flush() after the first print statement? Are print and sleep thread-safe? Or
is this a bug (I use python 3.1)

Any hints and help for an newbie would be appreciated.

Thanks,
Andi



More information about the Python-list mailing list