print statement and multithreading

David Bolen db3l at fitlinxx.com
Tue Aug 22 17:36:32 EDT 2000


"Quasimodo" <KILLzdramboSPAMMERS at zdnetmail.com> writes:

> or any other combination of the above.  The only way I've been able to get
> around this (for now, not sure if it will hold true) is to assign the entire
> print output to a temp var and then print:
> 
> e.g.  temp = "123 " + x     #i.e. temp is now:  "123 456"
>          print temp
> 
> Maybe someone else knows a better way.

The problem is that print is processing each of its arguments as
separate output calls (if you've ever re-routed sys.stdout to your own
handler, you know it can be called several times for a single print),
and in betwee those operations other threads may run.

Putting it into a single argument to print (whether by building up a
string, or using a format string like "123 %s" % x) should minimize
this since print is just making one output call, but I think you could
still get interrupted before the newline.

Using sys.stdout.write() is probably safer since everything is
contained in a single string.

But safest (if you really need to ensure you can control exactly at
what granularity of output your output can shift between threads)
would be to set up a lock (locks are supported in the threading
module) to be used for stdout access.  Then, when you want to output
to stdout, acquire the lock, do the I/O and then release the lock.
This could be encapsulated into a class that you re-route stdout to so
you wouldn't have to think about it.  Of course, that class would have
to decide when to actually generate the output within the lock (e.g.,
it might wait for the newline to output a single line as a unit).

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list