을 찾는 방법에 스레드 id Python
-
06-09-2019 - |
문제
나는 멀티-스레딩 프로그램,그리고 유틸리티 기능 writeLog(message)
, 는 씁니다 타임스탬프 뒤 메시지입니다.불행하게도,결과 로그 파일의 징후를 제공하지 않는 스레드를 생성하는 메시지입니다.
I would like writeLog()
수있는 무언가를 추가하는 메시지를 식별하는 스레드가 호출니다.분명히 할 수 있게 만들레이 정보를 전달에서,그는 것은 더 많은 작동합니다.이 스레드당 os.getpid()
사용할 수 있는?
해결책
threading.get_ident()
작동,또는 threading.current_thread().ident
(나 threading.currentThread().ident
파이썬 < 2.6).
다른 팁
이 thread.get_ident()
반 긴 정수 리눅스에서.정말이지 않는 스레드 id.
내가 사용하는 이 방법 정말 스레드 id 에서 리눅스:
import ctypes
libc = ctypes.cdll.LoadLibrary('libc.so.6')
# System dependent, see e.g. /usr/include/x86_64-linux-gnu/asm/unistd_64.h
SYS_gettid = 186
def getThreadId():
"""Returns OS thread id - Specific to Linux"""
return libc.syscall(SYS_gettid)
본 예제의 스레드 Id 는 다음과 같다:
class myThread(threading.Thread):
def __init__(self, threadID, name, counter):
self.threadID = threadID
...
이 실을 꿰는 모듈 문서 목록 name
특성 뿐만 아니라:
...
A thread has a name.
The name can be passed to the constructor,
and read or changed through the name attribute.
...
Thread.name
A string used for identification purposes only.
It has no semantics. Multiple threads may
be given the same name. The initial name is set by the constructor.
당신이 얻을 수 있는 식의 현재 실행중인 thread.The ident 다시 사용할 수 있습니다 다른 스레드는 경우,현재 스레드가 종료됩니다.
할 때는 상자의 인스턴스 스레드,이름을 제공하는 암시적인 스레드는 패턴:실 번호
이름을 의미가 없습니다 이름과하지 않는 유일해야 한다.의 행선지의 모든 실행 스레드가 유일하다.
import threading
def worker():
print(threading.current_thread().name)
print(threading.get_ident())
threading.Thread(target=worker).start()
threading.Thread(target=worker, name='foo').start()
기능 threading.current_thread()현재 실행 스레드가 있습니다.이 객체를 보유하고 전체의 정보를 스레드가 있습니다.
내가 만들어 여러 스레드 라이브러리는 모두 지원되며,인쇄 실체,그리고 나는 인쇄를 사용하는 id ident
변수가 있습니다.나는 모든 id 는 동일합니다:
<Thread(Thread-1, stopped 140500807628544)>
<Thread(Thread-2, started 140500807628544)>
<Thread(Thread-3, started 140500807628544)>
마찬가지로@brucexin 나를 얻을하는 데 필요한 OS-level thread 식별자(!= thread.get_ident()
고)사용하여 아래와 같은에 의존하지 특정 숫자와 amd64-만:
---- 8< ---- (xos.pyx)
"""module xos complements standard module os"""
cdef extern from "<sys/syscall.h>":
long syscall(long number, ...)
const int SYS_gettid
# gettid returns current OS thread identifier.
def gettid():
return syscall(SYS_gettid)
고
---- 8< ---- (test.py)
import pyximport; pyximport.install()
import xos
...
print 'my tid: %d' % xos.gettid()
이에 따라 달라집 Cython 하지만입니다.