Bug? print statement ends with ',' print a new line

Peter Hansen peter at engcorp.com
Sat Jun 7 11:57:35 EDT 2003


Lu wrote:
> 
> C:\FAT32\py>type counter.py
> import sys
> import threading
> 
> class Counter:
>     def __init__(self,count=0):
>         self.count=count
>     def start(self):
>         if self.count>0:
>             print self.count,'.',
>             self.count-=1
>             t=threading.Timer(1,self.start)
>             t.start()
>         elif self.count==0:
>             print self.count
> 
> counter=Counter(int(sys.argv[1]))
> counter.start()
> 
> C:\FAT32\py>counter.py 5
> 5 .
> 4 . 3 . 2 . 1 . 0

I don't actually know what you're trying to do, but I don't
think it matters because you very likely have a race condition.
That's because you are executing the print statements from
two places, the main thread and the timer thread that
you start up (or is it multiple timer threads?... as I said,
I'm not even going to try to decipher the intent).

Note that "print" is not an atomic operation.  In fact,
each item that is printed is, I believe, a separate 
set of operations (one to retrieve the string representation,
one to do the actual printing).  Also, there is the "softspace"
mechanism which likely leads to additional bytecode operations
inside the same print statement.  With all that, and multiple
threads involved, you should expect to see unexpected results. :-)

-Peter




More information about the Python-list mailing list