Skip to content

Commit 4959c33

Browse files
jaketeslerpitrou
authored andcommitted
bpo-36084: Add native thread ID to threading.Thread objects (pythonGH-11993)
1 parent 87068ed commit 4959c33

File tree

10 files changed

+133
-2
lines changed

10 files changed

+133
-2
lines changed

Doc/library/_thread.rst

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,18 @@ This module defines the following constants and functions:
8585
may be recycled when a thread exits and another thread is created.
8686

8787

88+
.. function:: get_native_id()
89+
90+
Return the native integral Thread ID of the current thread assigned by the kernel.
91+
This is a non-negative integer.
92+
Its value may be used to uniquely identify this particular thread system-wide
93+
(until the thread terminates, after which the value may be recycled by the OS).
94+
95+
.. availability:: Windows, FreeBSD, Linux, macOS.
96+
97+
.. versionadded:: 3.8
98+
99+
88100
.. function:: stack_size([size])
89101

90102
Return the thread stack size used when creating new threads. The optional

Doc/library/threading.rst

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,18 @@ This module defines the following functions:
4949
.. versionadded:: 3.3
5050

5151

52+
.. function:: get_native_id()
53+
54+
Return the native integral Thread ID of the current thread assigned by the kernel.
55+
This is a non-negative integer.
56+
Its value may be used to uniquely identify this particular thread system-wide
57+
(until the thread terminates, after which the value may be recycled by the OS).
58+
59+
.. availability:: Windows, FreeBSD, Linux, macOS.
60+
61+
.. versionadded:: 3.8
62+
63+
5264
.. function:: enumerate()
5365

5466
Return a list of all :class:`Thread` objects currently alive. The list
@@ -297,6 +309,25 @@ since it is impossible to detect the termination of alien threads.
297309
another thread is created. The identifier is available even after the
298310
thread has exited.
299311

312+
.. attribute:: native_id
313+
314+
The native integral thread ID of this thread or ``0`` if the thread has not
315+
been started. This is a non-negative integer. See the
316+
:func:`get_native_id` function.
317+
This represents the Thread ID (``TID``) as assigned to the
318+
thread by the OS (kernel). Its value may be used to uniquely identify
319+
this particular thread system-wide.
320+
321+
.. note::
322+
323+
Similar to Process IDs, Thread IDs are only valid (guaranteed unique
324+
system-wide) from the time the thread is created until the thread
325+
has been terminated.
326+
327+
.. availability:: Windows, FreeBSD, Linux, macOS.
328+
329+
.. versionadded:: 3.8
330+
300331
.. method:: is_alive()
301332

302333
Return whether the thread is alive.

Include/pythread.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ PyAPI_FUNC(void) PyThread_init_thread(void);
2525
PyAPI_FUNC(unsigned long) PyThread_start_new_thread(void (*)(void *), void *);
2626
PyAPI_FUNC(void) _Py_NO_RETURN PyThread_exit_thread(void);
2727
PyAPI_FUNC(unsigned long) PyThread_get_thread_ident(void);
28+
PyAPI_FUNC(unsigned long) PyThread_get_thread_native_id(void);
2829

2930
PyAPI_FUNC(PyThread_type_lock) PyThread_allocate_lock(void);
3031
PyAPI_FUNC(void) PyThread_free_lock(PyThread_type_lock);

Lib/_dummy_thread.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,10 @@ def get_ident():
7171
"""
7272
return 1
7373

74+
def get_native_id():
75+
"""Dummy implementation of _thread.get_native_id()."""
76+
return 0
77+
7478
def allocate_lock():
7579
"""Dummy implementation of _thread.allocate_lock()."""
7680
return LockType()

Lib/test/test_threading.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,10 @@ def test_various_ops(self):
104104
self.assertRegex(repr(t), r'^<TestThread\(.*, initial\)>$')
105105
t.start()
106106

107+
native_ids = set(t.native_id for t in threads) | {threading.get_native_id()}
108+
self.assertNotIn(None, native_ids)
109+
self.assertEqual(len(native_ids), NUMTASKS + 1)
110+
107111
if verbose:
108112
print('waiting for all tasks to complete')
109113
for t in threads:

Lib/threading.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@
2323
# with the multiprocessing module, which doesn't provide the old
2424
# Java inspired names.
2525

26-
__all__ = ['get_ident', 'active_count', 'Condition', 'current_thread',
27-
'enumerate', 'main_thread', 'TIMEOUT_MAX',
26+
__all__ = ['get_ident', 'get_native_id', 'active_count', 'Condition',
27+
'current_thread', 'enumerate', 'main_thread', 'TIMEOUT_MAX',
2828
'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
2929
'Barrier', 'BrokenBarrierError', 'Timer', 'ThreadError',
3030
'setprofile', 'settrace', 'local', 'stack_size']
@@ -34,6 +34,7 @@
3434
_allocate_lock = _thread.allocate_lock
3535
_set_sentinel = _thread._set_sentinel
3636
get_ident = _thread.get_ident
37+
get_native_id = _thread.get_native_id
3738
ThreadError = _thread.error
3839
try:
3940
_CRLock = _thread.RLock
@@ -790,6 +791,7 @@ class is implemented.
790791
else:
791792
self._daemonic = current_thread().daemon
792793
self._ident = None
794+
self._native_id = 0
793795
self._tstate_lock = None
794796
self._started = Event()
795797
self._is_stopped = False
@@ -891,6 +893,9 @@ def _bootstrap(self):
891893
def _set_ident(self):
892894
self._ident = get_ident()
893895

896+
def _set_native_id(self):
897+
self._native_id = get_native_id()
898+
894899
def _set_tstate_lock(self):
895900
"""
896901
Set a lock object which will be released by the interpreter when
@@ -903,6 +908,7 @@ def _bootstrap_inner(self):
903908
try:
904909
self._set_ident()
905910
self._set_tstate_lock()
911+
self._set_native_id()
906912
self._started.set()
907913
with _active_limbo_lock:
908914
_active[self._ident] = self
@@ -1077,6 +1083,17 @@ def ident(self):
10771083
assert self._initialized, "Thread.__init__() not called"
10781084
return self._ident
10791085

1086+
@property
1087+
def native_id(self):
1088+
"""Native integral thread ID of this thread or 0 if it has not been started.
1089+
1090+
This is a non-negative integer. See the get_native_id() function.
1091+
This represents the Thread ID as reported by the kernel.
1092+
1093+
"""
1094+
assert self._initialized, "Thread.__init__() not called"
1095+
return self._native_id
1096+
10801097
def is_alive(self):
10811098
"""Return whether the thread is alive.
10821099
@@ -1176,6 +1193,7 @@ def __init__(self):
11761193
self._set_tstate_lock()
11771194
self._started.set()
11781195
self._set_ident()
1196+
self._set_native_id()
11791197
with _active_limbo_lock:
11801198
_active[self._ident] = self
11811199

@@ -1195,6 +1213,7 @@ def __init__(self):
11951213

11961214
self._started.set()
11971215
self._set_ident()
1216+
self._set_native_id()
11981217
with _active_limbo_lock:
11991218
_active[self._ident] = self
12001219

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add native thread ID (TID) to threading.Thread objects

Modules/_threadmodule.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1159,6 +1159,20 @@ allocated consecutive numbers starting at 1, this behavior should not\n\
11591159
be relied upon, and the number should be seen purely as a magic cookie.\n\
11601160
A thread's identity may be reused for another thread after it exits.");
11611161

1162+
static PyObject *
1163+
thread_get_native_id(PyObject *self, PyObject *Py_UNUSED(ignored))
1164+
{
1165+
unsigned long native_id = PyThread_get_thread_native_id();
1166+
return PyLong_FromUnsignedLong(native_id);
1167+
}
1168+
1169+
PyDoc_STRVAR(get_native_id_doc,
1170+
"get_native_id() -> integer\n\
1171+
\n\
1172+
Return a non-negative integer identifying the thread as reported\n\
1173+
by the OS (kernel). This may be used to uniquely identify a\n\
1174+
particular thread within a system.");
1175+
11621176
static PyObject *
11631177
thread__count(PyObject *self, PyObject *Py_UNUSED(ignored))
11641178
{
@@ -1310,6 +1324,8 @@ static PyMethodDef thread_methods[] = {
13101324
METH_NOARGS, interrupt_doc},
13111325
{"get_ident", thread_get_ident,
13121326
METH_NOARGS, get_ident_doc},
1327+
{"get_native_id", thread_get_native_id,
1328+
METH_NOARGS, get_native_id_doc},
13131329
{"_count", thread__count,
13141330
METH_NOARGS, _count_doc},
13151331
{"stack_size", (PyCFunction)thread_stack_size,

Python/thread_nt.h

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,8 @@ LeaveNonRecursiveMutex(PNRMUTEX mutex)
143143

144144
unsigned long PyThread_get_thread_ident(void);
145145

146+
unsigned long PyThread_get_thread_native_id(void);
147+
146148
/*
147149
* Initialization of the C package, should not be needed.
148150
*/
@@ -227,6 +229,20 @@ PyThread_get_thread_ident(void)
227229
return GetCurrentThreadId();
228230
}
229231

232+
/*
233+
* Return the native Thread ID (TID) of the calling thread.
234+
* The native ID of a thread is valid and guaranteed to be unique system-wide
235+
* from the time the thread is created until the thread has been terminated.
236+
*/
237+
unsigned long
238+
PyThread_get_thread_native_id(void)
239+
{
240+
if (!initialized)
241+
PyThread_init_thread();
242+
243+
return GetCurrentThreadId();
244+
}
245+
230246
void _Py_NO_RETURN
231247
PyThread_exit_thread(void)
232248
{

Python/thread_pthread.h

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@
1212
#endif
1313
#include <signal.h>
1414

15+
#if defined(__linux__)
16+
#include <sys/syscall.h>
17+
#elif defined(__FreeBSD__)
18+
#include <pthread_np.h>
19+
#endif
20+
1521
/* The POSIX spec requires that use of pthread_attr_setstacksize
1622
be conditional on _POSIX_THREAD_ATTR_STACKSIZE being defined. */
1723
#ifdef _POSIX_THREAD_ATTR_STACKSIZE
@@ -302,6 +308,27 @@ PyThread_get_thread_ident(void)
302308
return (unsigned long) threadid;
303309
}
304310

311+
unsigned long
312+
PyThread_get_thread_native_id(void)
313+
{
314+
if (!initialized)
315+
PyThread_init_thread();
316+
#ifdef __APPLE__
317+
uint64_t native_id;
318+
pthread_threadid_np(NULL, &native_id);
319+
#elif defined(__linux__)
320+
pid_t native_id;
321+
native_id = syscall(__NR_gettid);
322+
#elif defined(__FreeBSD__)
323+
pid_t native_id;
324+
native_id = pthread_getthreadid_np();
325+
#else
326+
unsigned long native_id;
327+
native_id = 0;
328+
#endif
329+
return (unsigned long) native_id;
330+
}
331+
305332
void _Py_NO_RETURN
306333
PyThread_exit_thread(void)
307334
{

0 commit comments

Comments
 (0)