Skip to content

Instantly share code, notes, and snippets.

@gaborbernat
Created December 3, 2020 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaborbernat/67b653f1d3ce4857a065a3bd81e424df to your computer and use it in GitHub Desktop.
Save gaborbernat/67b653f1d3ce4857a065a3bd81e424df to your computer and use it in GitHub Desktop.
"""The challenge here is to make grand children print out the value set by child, without access to modify cannot_modify"""
from threading import Thread, local, current_thread
# solution start
def new_start(self): # need to patch this
self.parent = current_thread().ident
old_start(self)
old_start, Thread.start = Thread.start, new_start
class Local(local):
threads = {}
def __init__(self):
parent = getattr(current_thread(), "parent", None)
self._update_thread_var(self.threads.get(parent, 'default'))
def _update_thread_var(self, value):
self._value = value
self.threads[current_thread().ident] = self._value
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._update_thread_var(value)
var = Local()
# solution end
def peek(from_name):
print(f"{from_name}: {var.value}\n", end="")
def master():
var.value = "master"
peek("master")
children = [Thread(target=child, name=name, args=(name,)) for name in ("A", "B")]
[t.start() for t in children]
[t.join() for t in children]
def child(name):
var.value = name
peek(name)
cannot_modify(name)
def cannot_modify(name):
thread = Thread(target=grand_child, name=f"{name}-{0}", args=(f"{name}-{0}",))
thread.start()
thread.join()
def grand_child(name):
peek(name)
master()
"""
master: master
A: A
A-0: A
B: B
B-0: B
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment