print in multithreaded environement ???

vincent_delft at yahoo.com vincent_delft at yahoo.com
Thu Feb 26 00:37:23 EST 2004


Thanks Josiah for the answer. 

but in my case each thread will have his own buffer and stdout will be
redirect to it.

Following your example, I think that what I'm talking about should be like
this :
import time
from threading import Thread
import sys
def funct(i):
     fid=open('/tmp/tt%s.tt' % i,'w')
     sys.stdout=fid
     for j in xrange(50):
        print i,j,
        time.sleep(0)
     fid.close()
for i in xrange(50): Thread(target=funct, args=(i,)).start()

If I run it, I've the result I expected: counter from 0 to 49 in each file.
Thus sys.stdout is not a shared object between each thread. It's his
redirection to the console which is common. 
Thus, problems occurs when we link it to a shared output (like a console or
single output file).

Am I correct ?




Josiah Carlson wrote:

>> Does sys.stdout is a seperate instance for each thread ?
>> Does sys.stdout is shared between all of them ?
> 
> sys.stdout, sys.stdin and sys.stderr are all shared.
> 
> 
>> Does any one has experience with that ?
> 
> Yes.  As soon as a thread uses up its timeslice, it is paused.  Sending
> a lot of information to sys.stdout, or doing any non-trivial computation
> is a good way of using up a timeslice...as is sleeping for an
> arbitrarily small amount of time, even 0.
> 
> Run the following code to see how it behaves.
> 
> import time
> from threading import Thread
> def funct(i):
>      for j in xrange(50):
>              print i,
>              time.sleep(0)
> 
> for i in xrange(50): Thread(target=funct, args=(i,)).start()
> 
> 
>   - Josiah




More information about the Python-list mailing list