Welcome, guest | Sign In | My Account | Store | Cart

<removed>

Python, 1 line
1
<removed>

<removed>

3 comments

Noah Spurrier 13 years, 10 months ago  # | flag

Could you expand on "with other_threads_suspended()"? Is this the right idea or can it be made even simpler?

import sys
from contextlib import contextmanager
@contextmanager
def other_threads_suspended():
    try:
        sys.setcheckinterval(sys.maxint)
        yield None
    finally:
        sys.setcheckinterval(100)

# Example usage:
with other_threads_suspended():
    print "Hello world!"

It would be nice to see an example running many threads printing at random intervals to demonstrate the problem of interleaved output. Then compare that output to an example that adds "with other_threads_suspended" around the print calls.

Noah Spurrier 13 years, 10 months ago  # | flag

Is there any guarantee that another thread will not be given context between the calls to sys.setcheckinterval(sys.maxint) and the print somevalue. How do we know that sys.setcheckinterval(sys.maxint) wasn't meant to be this current thread's last instruction before the GIL was to be released? Or, rather the last instruction in the byte code that makes up setcheckinterval(), but I think the idea is the same. It seems like you could have a race condition here. In other words, even though you have just finished setting the check interval much higher, could the context switch happen just as setcheckinterval finishes yet before Python starts using the new value to decide when to switch? You might be giving the next thread the gift of nearly exclusive execution -- worse yet, that thread doesn't know to set checkinterval back to 100, so it could be a long, long time before our original thread is given context again to finish printing and then setting the checkinterval back to something reasonable.

Josiah Carlson 12 years, 8 months ago  # | flag

I am sorry to say, but this recipe doesn't work in the general case: http://dr-josiah.blogspot.com/2011/07/neat-python-hack-no-broken-code.html . Users are better off using locks to not be surprised.

Created by Raymond Hettinger on Mon, 13 Mar 2006 (PSF)
Python recipes (4591)
Raymond Hettinger's recipes (97)
Rapid prototyping (11)

Required Modules

  • (none specified)

Other Information and Tasks