【问题标题】:How to identify thread from /proc using thread name?如何使用线程名称从 /proc 中识别线程?
【发布时间】:2018-06-15 00:25:48
【问题描述】:

我在我的 python 程序中使用线程名称创建多个线程。有什么方法可以从 /proc//task/* 中识别特定任务。我可以看到 /proc/17094/task/17095/comm 但它只打印我的程序名称而不是线程名称

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self, name=name)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        print "Starting " + self.name
        # Get lock to synchronize threads
        print_time(self.name, self.counter, 9)
        # Free lock to release next thread

    def print_time(threadName, delay, counter):
        while counter:
            time.sleep(delay+9)
            print "%s: %s" % (threadName, time.ctime(time.time()))
            threadLock.acquire()
            counter -= 1
            threadLock.release()

threadLock = threading.Lock()
threads = []

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()

# Add threads to thread list
threads.append(thread1)
threads.append(thread2)

print "Started both threads"
# Wait for all threads to complete
for t in threads:
    t.join()
print "Exiting Main Thread"

这里我想根据名字来查看线程 - Thread-1 -

我可以看到/proc/下的任务

~ # ps -ef | grep thread1
root     17787  4859  0 00:24 pts/0    00:00:00 /bin/python ./thread1.py
root     17800  4938  0 00:24 pts/1    00:00:00 grep thread1
~ # ls -l /proc/17787/task/
total 0
dr-xr-xr-x 7 root root 0 Jun 15 00:24 17787
dr-xr-xr-x 7 root root 0 Jun 15 00:24 17788
dr-xr-xr-x 7 root root 0 Jun 15 00:24 17789

但是我在这些目录下的任何文件中都看不到 Thread-1。

【问题讨论】:

    标签: python multithreading python-2.x python-multithreading


    【解决方案1】:

    首先,为您的线程命名。 https://linux.die.net/man/3/pthread_setname_np

    所以,在ps -ef | grep thread1 之后,您发现 pid 是 17787

    运行:

    ps -T -p 17787
    

    这将显示进程的线程。

    欲了解更多信息,man ps

    根据要求,按名称获取线程信息:

    cat /proc/pid/task/tid/comm
    

    其中 pid 是进程 ID,tid 是线程 ID(通配符 * 表示所有)

    【讨论】:

    • 感谢您的回复。但我的要求是使用线程名称查看线程的详细信息 - 我认为如果我们使用线程名称创建线程,名称应该出现在 /proc/ 目录下的任务目录中
    • cat /proc/11896/task/*/comm - 给出在我的 linux 服务器中运行的 trafficserver 的线程名称
    • cat /proc/pid/task/tid/comm 只给出程序名称,而不是线程名称。正如我在帖子中提到的,我期待“Thread-1”和“Thread-2”。
    • 是的,你把通配符放在你发现的所有地方,我只写了语法
    • 如果我以python myprogram.py 执行我的程序,cat /proc/pid/task/tid/comm 将仅显示“python”。但我想将其视为“Thread-1”,因为这是我为线程指定的名称。
    猜你喜欢
    • 2021-12-04
    • 2011-07-02
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 2011-06-20
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多