2013-09-26 20 views
0

如何能夠接受當前線程對象?
考慮這個有點人爲的代碼片段。用例是不同的,但是爲了簡單起見,我已經熬下來的必要位反思python中的當前線程

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 
+0

threading.currentThread()給你當前的線程,還是你需要更多的?線程本地數據可用於標記線程。 (也許我誤解了你的意圖) –

回答

1

可以使用thread.get_ident功能。與Thread.ident比較thread.get_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

爲了使最小的改動你的代碼,這裏可能是你所追求的:

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()訪問。

+0

「在計算機編程中,內省是指能夠檢查某些事物以確定它是什麼,它知道什麼以及它有能力做什麼。」 ([源(http://www.ibm.com/developerworks/library/l-pyint/index.html))。在我們的例子中,代碼正在反思它正在運行的線程。 – Jonathan

+0

這個定義太寬泛了。幾乎任何程序都可能使用自省。可能是反思是我內省的理解的更好的術語:https://en.wikipedia.org/wiki/Reflection_%28computer_programming%29,但仍然訪問線程對象很難稱爲自省/反思... –