how do I make a 2.7 python context manager threadsafe how do I make a 2.7 python context manager threadsafe multithreading multithreading

how do I make a 2.7 python context manager threadsafe


Here is a way that seems to work: make your OverrideTests class a subclass of threading.local. For safety, you should then call the superclass __init__ in your __init__ (although it seems to work even if you don't):

class OverrideTests(threading.local):    def __init__(self):        super(OverrideTests, self).__init__()        self.override = 0    # rest of class same as beforeoverride_tests = OverrideTests()

Then:

>>> do_it_lots()1.1.1.2.2.1.1.1.1.1.1.3.3.2.2.2.2.2.2.4.4.3.1.3.3.3.3.4.3.2.4.4.2.4.3.4.4.4.3.4.

However, I wouldn't put money on this not failing in some kind of corner case, especially if your real application is more complex than the example you showed here. Ultimately, you really should rethink your design. In your question, you are focusing on how to "make the context-manager threadsafe". But the real problem is not just with your context manager but with your function (stat in your example). stat is relying on global state (the global override_tests), which is inherently fragile in a threaded environment.