print statement and multithreading

Ken Kinder kkinder at tridog.com
Tue Aug 22 13:25:13 EDT 2000


It's hard to say. I _think_ the buffer flushes at newline. Something
I've done for logging, when multiple threads are running, is create a
class that worries about it for you. Something like this (untested)...

class Logger:
    def __init__(self, auto_flush=1):
        self.messages = []
        self.buffer_lock = thread.allocate_lock()
        self.continue = 1
        if auto_flush:
            thread.start_new_thread(self.autoflusher, [])

    def autoflusher(self):
        while continue:
            sleep(10)
            self.flush()

    def __del__(self):
        self.continue = 0

    def flush(self):
        self.buffer_lock.acquire()
        for message in self.messages:
            print message  # Or whatever
        self.buffer_lock.release()

    def write(self, message):
        self.buffer_lock.acquire()
        self.messages.append(message)
        self.buffer_lock.release()

Matthew Schroeder wrote:
> 
> that could be, if the IO streams are buffering the output, because they'd
> flush at different times.
> 
> In Perl we were able to specify autoflush for the buffers, which would keep
> them in order, as they wouldn't buffer output then.
> 
> I don't know if you can do the same in Python though.
> 
> -----Original Message-----
> From: Ken Kinder [mailto:kkinder at tridog.com]
> Sent: Tuesday, August 22, 2000 12:40 PM
> To: Roy Katz
> Cc: python-list at python.org
> Subject: Re: print statement and multithreading
> 
> It should work the same. The only thing you might worry a little about
> is the order things come out -- sometimes i/o streams seem out of order.

-- 
Ken Kinder
Staff Engineer - Tridog Interactive, Inc.
kkinder at tridog.com
http://www.tridog.com/ - 303-415-2538
-------------- next part --------------
A non-text attachment was scrubbed...
Name: kkinder.vcf
Type: text/x-vcard
Size: 257 bytes
Desc: Card for Ken Kinder
URL: <http://mail.python.org/pipermail/python-list/attachments/20000822/53be00e5/attachment.vcf>


More information about the Python-list mailing list