你可以使用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)