Is print thread safe?
Cameron Simpson
cs at zip.com.au
Tue Aug 12 02:15:20 EDT 2014
On 12Aug2014 08:01, Marko Rauhamaa <marko at pacujo.net> wrote:
>Steven D'Aprano <steve+comp.lang.python at pearwood.info>:
>> Personally, I believe that print ought to do its own locking. And
>> print is a statement, although in this case there's no need to support
>> anything older than 2.6, so something like this ought to work:
>>
>> from __future__ import print_function
>>
>> _print = print
>> _rlock = threading.RLock()
>> def print(*args, **kwargs):
>> with _rlock:
>> _print(*args, **kwargs)
>
>Could this cause a deadlock if print were used in signal handlers?
At the C level one tries to do as little as possible in q signal handler.
Typically setting a flag or putting something on a queue for later work.
In Python that may be a much smaller issue, since I imagine the handler runs in
the ordinary course of interpretation, outside the C-level handler context.
I personally wouldn't care if this might deadlock in a handler (lots of things
might; avoid as many things as possible). Also, the code above uses an RLock;
less prone to deadlock than a plain mutex Lock.
Cheers,
Cameron Simpson <cs at zip.com.au>
A host is a host from coast to coast
& no one will talk to a host that's close
Unless the host (that isn't close)
is busy, hung or dead
- David Lesher, wb8foz at skybridge.scl.cwru.edu
More information about the Python-list
mailing list