首页 > 解决方案 > 使用 pthread_setname_np 时出现分段错误

问题描述

我正在尝试使用 python 中的线程名称 libpthread.pthread_setname_np 函数来修补线程名称,就像这样

'''

libpthread = ctypes.CDLL("libpthread.so")
if not libpthread:
    # no pthread library, not patching
    return

if not hasattr(libpthread, "pthread_setname_np"):
    # pthread library does not have pthread_setname_np function, not patching
    return

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 start(self):
    """Patched version of threading.Thread.start"""
    orig_start(self)
    try:
        name = self.name
        if name:
            if hasattr(name, "encode"):
                name = name.encode('ascii', 'replace')
            ident = getattr(self, "ident", None)
            if ident is not None:
                pthread_setname_np(ident, name[:15])
    except Exception: # pylint: disable=broad-except
        pass  # Don't care about failure to set name

'''

以下代码通过以下消息证明我存在分段错误。

libpthread-2.31.so 中的段错误 4

关于可能导致此问题的任何输入。

标签: pythonpthreadspython-multithreading

解决方案


推荐阅读