You are viewing bramcohen

Fri, Oct. 16th, 2009, 10:09 am
print isn't even vaguely thread safe

Thanks to everyone who provided suggestions for my problems with print yesterday. It turns out that print isn't even vaguely threadsafe, and that the rather surprising behavior when there's a collision is for there to be duplicate output bytes. So if you ever see duplicate print lines, you know what to guess it is now.

My quick hack for getting around the problem is to make a module called rprint which looks like this (I'm using python 3):
from threading import Lock

mylock = Lock()
p = print

def print(*a, **b):
	with mylock:
		p(*a, **b)
Then from every module where I have a print I say:
from rprint import print
I don't know if this is an elegant solution or an ugly hack, but hey it works.

Fri, Oct. 16th, 2009 06:55 pm (UTC)

I would go for elegant solution, particularly because it isn't too much code.

I've just had a search through some logs, and I have a horrible feeling I might have had some experiments with (fortunately only slightly) incorrect results because of this -- of course you could argue I shouldn't have had multiple threads chucking out print statements, but I wouldn't have expected multiple lines to occur.