Re: Please help with Threading

Discussion in 'Python' started by Cameron Simpson, May 20, 2013.

  1. On 20May2013 10:53, Carlos Nepomuceno <> 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 <>

    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"
    Cameron Simpson, May 20, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. KK
    Replies:
    2
    Views:
    512
    Big Brian
    Oct 14, 2003
  2. Replies:
    9
    Views:
    1,008
    Mark Space
    Dec 29, 2007
  3. silkenpy
    Replies:
    1
    Views:
    344
    Dennis Lee Bieber
    Feb 15, 2008
  4. Steven Woody
    Replies:
    0
    Views:
    393
    Steven Woody
    Jan 9, 2009
  5. Steven Woody
    Replies:
    0
    Views:
    432
    Steven Woody
    Jan 9, 2009
Loading...

Share This Page