[Tutor] IOError: (0, 'Error')

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Jan 2 23:15:35 CET 2006


> I think I see where you are going with this. Are you suggesting that
> both parent and child thread might be trying to write to the log at
> once, and one of them is closing the file while it is open for both?

Hi Bernard,

One possibility is that we have a shared resource that needs some kind of
mutual exclusion.  If two threads try to append directly to the file, I
don't know what will happen, but the result will probably not be good.


But the Queue module can be especially useful here:

    http://www.python.org/doc/lib/module-Queue.html

The idea is that we keep a separate logger thread that reads messages off
a Queue instance.  Something like:

######
queue = Queue()
def __loggerThreadLoop(self):
    while True:
        (sMsg, iLevel) = queue.get()
        if iLevel <= self.loglevel:
             ... the rest of the original contents of __nodeLog

######

and we can just start up a thread that starts up __loggerThreadLoop(),
somewhere in your instance's constructor:

    threading.Thread(target=self.__loggerThreadLoop).start()

Initially, the queue is empty, so that logger thread sleeps till it sees a
new message on the queue.  __nodeLog() itself becomes a simple queuing
function that just pushes new log events to the queue.

If we do this, then we guarantee that only one thread is trying to write
to the log file at any time: the use of the Queue serializes our access to
it.  Does this make sense?



More information about the Tutor mailing list