0

如何自省接收当前线程对象?
考虑一下这个有点人为的代码片段。用例不同,但为了简单起见,我将其归结为基本部分

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
4

2 回答 2

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().

于 2013-09-26T15:27:45.200 回答
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)
于 2013-09-26T15:17:09.540 回答