Skip to content

Commit 7a4de5f

Browse files
committed
Move pthread_t to ident conversion to a shared function
Move this to a static function so all callers have consistent behavior. Signed-off-by: Vincent Fazio <[email protected]>
1 parent b93868e commit 7a4de5f

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

Python/thread_pthread.h

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -306,16 +306,34 @@ do_start_joinable_thread(void (*func)(void *), void *arg, pthread_t* out_id)
306306
return 0;
307307
}
308308

309+
/* Helper to convert pthread_t to PyThread_ident_t. POSIX allows pthread_t to be
310+
non-arithmetic, e.g., musl typedefs it as a pointer */
311+
static PyThread_ident_t
312+
_pthread_t_to_ident(pthread_t value) {
313+
#if SIZEOF_PTHREAD_T > SIZEOF_LONG
314+
return (PyThread_ident_t) *(unsigned long *) &value;
315+
#else
316+
PyThread_ident_t ident;
317+
#if defined(__linux__) && !defined(__GLIBC__)
318+
ident = (PyThread_ident_t) (uintptr_t) value;
319+
assert(pthread_equal(value, (pthread_t) (uintptr_t) ident));
320+
#else
321+
ident = (PyThread_ident_t) value;
322+
assert(pthread_equal(value, (pthread_t) ident));
323+
#endif
324+
return ident;
325+
#endif // SIZEOF_PTHREAD_T > SIZEOF_LONG
326+
}
327+
309328
int
310329
PyThread_start_joinable_thread(void (*func)(void *), void *arg,
311330
PyThread_ident_t* ident, PyThread_handle_t* handle) {
312331
pthread_t th = (pthread_t) 0;
313332
if (do_start_joinable_thread(func, arg, &th)) {
314333
return -1;
315334
}
316-
*ident = (PyThread_ident_t) th;
335+
*ident = _pthread_t_to_ident(th);
317336
*handle = (PyThread_handle_t) th;
318-
assert(th == (pthread_t) *ident);
319337
assert(th == (pthread_t) *handle);
320338
return 0;
321339
}
@@ -328,11 +346,7 @@ PyThread_start_new_thread(void (*func)(void *), void *arg)
328346
return PYTHREAD_INVALID_THREAD_ID;
329347
}
330348
pthread_detach(th);
331-
#if SIZEOF_PTHREAD_T <= SIZEOF_LONG
332-
return (unsigned long) th;
333-
#else
334-
return (unsigned long) *(unsigned long *) &th;
335-
#endif
349+
return (unsigned long) _pthread_t_to_ident(th);;
336350
}
337351

338352
int
@@ -357,8 +371,7 @@ PyThread_get_thread_ident_ex(void) {
357371
if (!initialized)
358372
PyThread_init_thread();
359373
threadid = pthread_self();
360-
assert(threadid == (pthread_t) (PyThread_ident_t) threadid);
361-
return (PyThread_ident_t) threadid;
374+
return _pthread_t_to_ident(threadid);
362375
}
363376

364377
unsigned long

0 commit comments

Comments
 (0)