1 """Implements the standard threading module, using greenthreads."""
2 from eventlet import patcher
3 from eventlet.green import thread
4 from eventlet.green import time
5 from eventlet.support import greenlets as greenlet, six
7 __patched__ = ['_start_new_thread', '_allocate_lock',
8 '_sleep', 'local', 'stack_size', 'Lock', 'currentThread',
9 'current_thread', '_after_fork', '_shutdown']
12 __patched__ += ['_get_ident']
14 __patched__ += ['get_ident', '_set_sentinel']
16 __orig_threading = patcher.original('threading')
17 __threadlocal = __orig_threading.local()
23 ('thread' if six.PY2 else '_thread', thread),
32 class _GreenThread(object):
33 """Wrapper for GreenThread objects to provide Thread-like attributes
36 def __init__(self, g):
39 self._name = 'GreenThread-%d' % _count
43 return '<_GreenThread(%s, %r)>' % (self._name, self._g)
45 def join(self, timeout=None):
52 def setName(self, name):
53 self._name = str(name)
56 name = property(getName, setName)
58 ident = property(lambda self: id(self._g))
64 daemon = property(lambda self: True)
75 # Some third-party packages (lockfile) will try to patch the
76 # threading.Thread class with a get_name attribute if it doesn't
77 # exist. Since we might return Thread objects from the original
78 # threading package that won't get patched, let's make sure each
79 # individual object gets patched too our patched threading.Thread
80 # class has been patched. This is why monkey patching can be bad...
83 __threading = __import__('threading')
85 if (hasattr(__threading.Thread, 'get_name') and
86 not hasattr(t, 'get_name')):
87 t.get_name = t.getName
92 g = greenlet.getcurrent()
94 # Not currently in a greenthread, fall back to standard function
95 return _fixup_thread(__orig_threading.current_thread())
98 active = __threadlocal.active
99 except AttributeError:
100 active = __threadlocal.active = {}
105 # Add green thread to active if we can clean it up on exit
110 except AttributeError:
111 # Not a GreenThread type, so there's no way to hook into
112 # the green thread exiting. Fall back to the standard
114 t = _fixup_thread(__orig_threading.currentThread())
116 t = active[id(g)] = _GreenThread(g)
120 currentThread = current_thread