From 1abbe27bd87d5e3aa863ae4d40b536485f300ece Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Thu, 6 Nov 2014 16:28:05 +0530 Subject: [PATCH] Linux: Name all threads started by calibre at the OS level for nicer debugging --- src/calibre/startup.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/calibre/startup.py b/src/calibre/startup.py index 5f3abaf898..ceb1ae502f 100644 --- a/src/calibre/startup.py +++ b/src/calibre/startup.py @@ -193,6 +193,36 @@ if not _run_once: __builtin__.__dict__['icu_upper'] = icu_upper __builtin__.__dict__['icu_title'] = title_case + if islinux: + # Name all threads at the OS level created using the threading module, see + # http://bugs.python.org/issue15500 + import ctypes, ctypes.util, threading + libpthread_path = ctypes.util.find_library("pthread") + if libpthread_path: + libpthread = ctypes.CDLL(libpthread_path) + if hasattr(libpthread, "pthread_setname_np"): + pthread_setname_np = libpthread.pthread_setname_np + pthread_setname_np.argtypes = [ctypes.c_void_p, ctypes.c_char_p] + pthread_setname_np.restype = ctypes.c_int + orig_start = threading.Thread.start + def new_start(self): + orig_start(self) + try: + name = self.name + if not name or name.startswith('Thread-'): + name = self.__class__.__name__ + if name == 'Thread': + name = self.name + if name: + if isinstance(name, unicode): + name = name.encode('ascii', 'replace') + ident = getattr(self, "ident", None) + if ident is not None: + pthread_setname_np(ident, name[:15]) + except Exception: + pass # Don't care about failure to set name + threading.Thread.start = new_start + def test_lopen(): from calibre.ptempfile import TemporaryDirectory from calibre import CurrentDir