Created
May 27, 2016 01:19
-
-
Save mnjul/82151862f7c9585dcea616a7e2e82033 to your computer and use it in GitHub Desktop.
Python Thread Local Storage "global instantiation" vs "thread-local accessing"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# python 2.7.6 | |
import threading | |
import sys | |
import traceback | |
import random | |
# too lazy to properly turn off output buffering | |
def msg(msg): | |
sys.stderr.write(msg) | |
sys.stderr.flush() | |
class Storage(threading.local): | |
def __init__(self): | |
ident = threading.current_thread().ident | |
msg('Thread %x: init -> %s\n' % (ident, ''.join(traceback.format_stack()))) | |
threading.local.__init__(self) | |
self.storage = {} | |
def get(self, k): | |
return self.storage.get(k) | |
def set(self, k, v): | |
self.storage[k] = v | |
storage = Storage() | |
class Runner(threading.Thread): | |
def run(self): | |
global storage | |
value = random.randint(1, 1000000) | |
ident = threading.current_thread().ident | |
msg('Thread %x: write %d\n' % (ident, value)) | |
storage.set('keykey', value) | |
read_value = storage.get('keykey') | |
msg('Thread %x: read %d, correct=%s\n' % (ident, read_value, read_value == value)) | |
threads = [Runner() for i in xrange(10)] | |
for thread in threads: | |
thread.start() | |
for thread in threads: | |
thread.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: