Debian Codegraph @

pypy/module/thread/threadlocals.py

raw symbols SCIP
1 import weakref
2 from rpython.rlib import rthread, rshrinklist
3 from rpython.rlib.objectmodel import we_are_translated
4 from rpython.rlib.rarithmetic import r_ulonglong
5 from pypy.module.thread.error import wrap_thread_error
6 from pypy.interpreter.executioncontext import ExecutionContext
7
8
9 ExecutionContext._signals_enabled = 0 # default value
10 ExecutionContext._sentinel_lock = None
11
12
13 class OSThreadLocals:
14 """Thread-local storage for OS-level threads.
15 For memory management, this version depends on explicit notification when
16 a thread finishes. This works as long as the thread was started by
17 os_thread.bootstrap()."""
18
19 def __init__(self, space):
20 "NOT_RPYTHON"
21 #
22 # This object tracks code that enters and leaves threads.
23 # There are two APIs. For Python-level threads, we know when
24 # the thread starts and ends, and we call enter_thread() and
25 # leave_thread(). In a few other cases, like callbacks, we
26 # might be running in some never-seen-before thread: in this
27 # case, the callback logic needs to call try_enter_thread() at
28 # the start, and if this returns True it needs to call
29 # leave_thread() at the end.
30 #
31 # We implement an optimization for the second case (which only
32 # works if we translate with a framework GC and with
33 # rweakref). If try_enter_thread() is called in a
34 # never-seen-before thread, it still returns False and
35 # remembers the ExecutionContext with 'self._weaklist'. The
36 # next time we call try_enter_thread() again in the same
37 # thread, the ExecutionContext is reused. The optimization is
38 # not completely invisible to the user: 'thread._local()'
39 # values will remain. We can argue that it is the correct
40 # behavior to do that, and the behavior we get if the
41 # optimization is disabled is buggy (but hard to do better
42 # then).
43 #
44 # 'self._valuedict' is a dict mapping the thread idents to
45 # ExecutionContexts; it does not list the ExecutionContexts
46 # which are in 'self._weaklist'. (The latter is more precisely
47 # a list of AutoFreeECWrapper objects, defined below, which
48 # each references the ExecutionContext.)
49 #
50 self.space = space
51 self._valuedict = {}
52 self._cleanup_()
53 self.raw_thread_local = rthread.ThreadLocalReference(ExecutionContext,
54 loop_invariant=True)
55
56 def can_optimize_with_weaklist(self):
57 config = self.space.config
58 return (config.translation.rweakref and
59 rthread.ThreadLocalReference.automatic_keepalive(config))
60
61 def _cleanup_(self):
62 self._valuedict.clear()
63 self._weaklist = None
64 self._mainthreadident = 0
65
66 def enter_thread(self, space):
67 "Notification that the current thread is about to start running."
68 self._set_ec(space.createexecutioncontext())
69
70 def try_enter_thread(self, space):
71 # common case: the thread-local has already got a value
72 if self.raw_thread_local.get() is not None:
73 return False
74
75 # Else, make and attach a new ExecutionContext
76 ec = space.createexecutioncontext()
77 if not self.can_optimize_with_weaklist():
78 self._set_ec(ec)
79 return True
80
81 # If can_optimize_with_weaklist(), then 'rthread' keeps the
82 # thread-local values alive until the end of the thread. Use
83 # AutoFreeECWrapper as an object with a __del__; when this
84 # __del__ is called, it means the thread was really finished.
85 # In this case we don't want leave_thread() to be called
86 # explicitly, so we return False.
87 if self._weaklist is None:
88 self._weaklist = ListECWrappers()
89 self._weaklist.append(weakref.ref(AutoFreeECWrapper(ec)))
90 self._set_ec(ec, register_in_valuedict=False)
91 return False
92
93 def _set_ec(self, ec, register_in_valuedict=True):
94 ident = rthread.get_ident()
95 if self._mainthreadident == 0 or self._mainthreadident == ident:
96 ec._signals_enabled = 1 # the main thread is enabled
97 self._mainthreadident = ident
98 if register_in_valuedict:
99 self._valuedict[ident] = ec
100 self.raw_thread_local.set(ec)
101
102 def leave_thread(self, space):
103 "Notification that the current thread is about to stop."
104 from pypy.module.thread.os_local import thread_is_stopping
105 ec = self.get_ec()
106 if ec is not None:
107 try:
108 thread_is_stopping(ec)
109 finally:
110 self.raw_thread_local.set(None)
111 ident = rthread.get_ident()
112 try:
113 del self._valuedict[ident]
114 except KeyError:
115 pass
116
117 def get_ec(self):
118 ec = self.raw_thread_local.get()
119 if not we_are_translated():
120 assert ec is self._valuedict.get(rthread.get_ident(), None)
121 return ec
122
123 def signals_enabled(self):
124 ec = self.get_ec()
125 return ec is not None and ec._signals_enabled
126
127 def enable_signals(self, space):
128 ec = self.get_ec()
129 assert ec is not None
130 ec._signals_enabled += 1
131
132 def disable_signals(self, space):
133 ec = self.get_ec()
134 assert ec is not None
135 new = ec._signals_enabled - 1
136 if new < 0:
137 raise wrap_thread_error(space,
138 "cannot disable signals in thread not enabled for signals")
139 ec._signals_enabled = new
140
141 def getallvalues(self):
142 if self._weaklist is None:
143 return self._valuedict
144 # This logic walks the 'self._weaklist' list and adds the
145 # ExecutionContexts to 'result'. We are careful in case there
146 # are two AutoFreeECWrappers in the list which have the same
147 # 'ident'; in this case we must keep the most recent one (the
148 # older one should be deleted soon). Moreover, entries in
149 # self._valuedict have priority because they are never
150 # outdated.
151 result = {}
152 for h in self._weaklist.items():
153 wrapper = h()
154 if wrapper is not None and not wrapper.deleted:
155 result[wrapper.ident] = wrapper.ec
156 # ^^ this possibly overwrites an older ec
157 result.update(self._valuedict)
158 return result
159
160 def reinit_threads(self, space):
161 "Called in the child process after a fork()"
162 ident = rthread.get_ident()
163 ec = self.get_ec()
164 assert ec is not None
165 old_sig = ec._signals_enabled
166 if ident != self._mainthreadident:
167 old_sig += 1
168 self._cleanup_() # clears self._valuedict
169 self._mainthreadident = ident
170 self._set_ec(ec)
171 ec._signals_enabled = old_sig
172
173
174 class AutoFreeECWrapper(object):
175 deleted = False
176
177 def __init__(self, ec):
178 # this makes a loop between 'self' and 'ec'. It should not prevent
179 # the __del__ method here from being called.
180 self.ec = ec
181 ec._threadlocals_auto_free = self
182 self.ident = rthread.get_ident()
183
184 def __del__(self):
185 from pypy.module.thread.os_local import thread_is_stopping
186 # this is always called in another thread: the thread
187 # referenced by 'self.ec' has finished at that point, and
188 # we're just after the GC which finds no more references to
189 # 'ec' (and thus to 'self').
190 self.deleted = True
191 thread_is_stopping(self.ec)
192
193 class ListECWrappers(rshrinklist.AbstractShrinkList):
194 def must_keep(self, wref):
195 return wref() is not None