我正在尝试使用对象的句柄从线程的上下文中调用线程对象的方法之一。但是,这不起作用,而是从主线程的上下文中调用该方法。有没有办法解决?
这是一些示例代码:
import threading
class ThreadTest(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
print '\nInitializing ThreadTest\n'
def call_me(self):
ident = threading.current_thread().ident
print '\nI was called from thread ' + str(ident) + '\n'
def run(self):
ident = threading.current_thread().ident
print '\nStarting thread ' + str(ident) + ' for ThreadTest\n'
self.call_me()
ident = threading.current_thread().ident
print '\nMain thread ID is ' + str(ident) + '\n'
tt = ThreadTest()
tt.start()
tt.call_me()
# Example Output:
# Main thread ID is 140735128459616
#
# Initializing ThreadTest
#
# Starting thread 4400537600 for ThreadTest
#
# I was called from thread 4400537600
#
# I was called from thread 140735128459616
我正在寻找的是一种tt.call_me()
从线程的上下文中创建的方法,以便current_thread().ident
返回与从线程的 run 方法调用时相同的 ID。
有任何想法吗?