Please help with Threading
Cameron Simpson
cs at zip.com.au
Mon May 20 04:35:20 EDT 2013
On 20May2013 10:53, Carlos Nepomuceno <carlosnepomuceno at outlook.com> wrote:
| I just got my hands dirty trying to synchronize Python prints from many threads.
| Sometimes they mess up when printing the newlines.
| I tried several approaches using threading.Lock and Condition.
| None of them worked perfectly and all of them made the code sluggish.
Show us some code, with specific complaints.
Did you try this?
_lock = Lock()
def lprint(*a, **kw):
global _lock
with _lock:
print(*a, **kw)
and use lprint() everywhere?
For generality the lock should be per file: the above hack uses one
lock for any file, so that's going to stall overlapping prints to
different files; inefficient.
There are other things than the above, but at least individual prints will
never overlap. If you have interleaved prints, show us.
| Is there a 100% sure method to make print thread safe? Can it be fast???
Depends on what you mean by "fast". It will be slower than code
with no lock; how much would require measurement.
Cheers,
--
Cameron Simpson <cs at zip.com.au>
My own suspicion is that the universe is not only queerer than we suppose,
but queerer than we *can* suppose.
- J.B.S. Haldane "On Being the Right Size"
in the (1928) book "Possible Worlds"
More information about the Python-list
mailing list