@@ -52,6 +52,15 @@ def get_thread_resource_usage():
5252 return None
5353
5454
55+ # get an id for the current thread.
56+ #
57+ # threading.get_ident doesn't actually return an OS-level tid, and annoyingly,
58+ # on Linux it actually returns the same value either side of a fork() call. However
59+ # we only fork in one place, so it's not worth the hoop-jumping to get a real tid.
60+ #
61+ get_thread_id = threading .get_ident
62+
63+
5564class ContextResourceUsage (object ):
5665 """Object for tracking the resources used by a log context
5766
@@ -225,7 +234,7 @@ def __init__(self, name=None, parent_context=None, request=None):
225234 # became active.
226235 self .usage_start = None
227236
228- self .main_thread = threading . current_thread ()
237+ self .main_thread = get_thread_id ()
229238 self .request = None
230239 self .tag = ""
231240 self .alive = True
@@ -318,7 +327,7 @@ def copy_to(self, record):
318327 record .request = self .request
319328
320329 def start (self ):
321- if threading . current_thread () is not self .main_thread :
330+ if get_thread_id () != self .main_thread :
322331 logger .warning ("Started logcontext %s on different thread" , self )
323332 return
324333
@@ -328,7 +337,7 @@ def start(self):
328337 self .usage_start = get_thread_resource_usage ()
329338
330339 def stop (self ):
331- if threading . current_thread () is not self .main_thread :
340+ if get_thread_id () != self .main_thread :
332341 logger .warning ("Stopped logcontext %s on different thread" , self )
333342 return
334343
@@ -355,7 +364,7 @@ def get_resource_usage(self):
355364
356365 # If we are on the correct thread and we're currently running then we
357366 # can include resource usage so far.
358- is_main_thread = threading . current_thread () is self .main_thread
367+ is_main_thread = get_thread_id () == self .main_thread
359368 if self .alive and self .usage_start and is_main_thread :
360369 utime_delta , stime_delta = self ._get_cputime ()
361370 res .ru_utime += utime_delta
0 commit comments