内省python中的当前线程

时间:2013-09-26 15:04:01

标签: python multithreading introspection

如何才能检测到接收当前线程对象?
考虑这个有点人为的代码片段。用例是不同的,但为了简单起见,我把它归结为基本位

t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)

marked_thread_for_cancellation = t1

t1.start()
t2.start()

def func():
    if [get_thread_obj] is marked_thread_for_cancellation:   # <== introspect here
        return
    # do something

2 个答案:

答案 0 :(得分:1)

您可以使用thread.get_ident功能。将thread.get_ident()Thread.ident进行比较,如下所示:

import thread
import threading
import time

marked_thread_for_cancellation = None

def func(identifier):
    while threading.get_ident() != marked_thread_for_cancellation:
        time.sleep(1)
        print('{} is alive'.format(identifier))
    print('{} is dead'.format(identifier))

t1 = threading.Thread(target=func, args=(1,))
t2 = threading.Thread(target=func, args=(2,))
t1.start()
t2.start()
time.sleep(2)
marked_thread_for_cancellation = t1.ident # Stop t1

在Python 3中,使用threading.get_ident

您也可以使用自己的标识符代替thread.get_ident

import threading
import time

marked_thread_for_cancellation = None

def func(identifier):
    while identifier != marked_thread_for_cancellation:
        time.sleep(1)
        print('{} is alive'.format(identifier))
    print('{} is dead'.format(identifier))

t1 = threading.Thread(target=func, args=(1,))
t2 = threading.Thread(target=func, args=(2,))
t1.start()
t2.start()
time.sleep(2)
marked_thread_for_cancellation = 1 # Stop t1 (`1` is the identifier for t1)

答案 1 :(得分:1)

要对代码进行微小的更改,这可能就是您的目标:

import threading

def func():
    if threading.current_thread() is marked_thread_for_cancellation:   # <== introspect here
        print 'cancel'
    else:
        print 'otherwise'

t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)

marked_thread_for_cancellation = t1

t1.start()
t2.start()

但我不明白内省是什么意思。 marked_thread_for_cancellation由所有线程共享,所有线程都有自己的一些本地数据,可通过threading.local()访问。