如何使用线程名称从/ proc识别线程?

时间:2018-06-15 00:25:49

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

我在我的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。

1 个答案:

答案 0 :(得分: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(所有的通配符*)