从线程上下文调用线程对象的方法

0 投票
1 回答
978 浏览
提问于 2025-04-17 15:40

我想在一个线程对象的上下文中,使用这个对象的句柄来调用它的方法。但是,这个方法调用并没有在我想要的线程中执行,而是从主线程中执行的。有没有什么办法可以解决这个问题呢?

下面是一些示例代码:

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 返回的ID就和在线程的运行方法中调用时返回的ID一样。

有什么想法吗?

1 个回答

0

Python中的类方法可以在任何线程中被调用,包括线程类threading.Thread。当你写了:

tt.call_me()

这其实是在说:“无论哪个线程在运行这段代码,请调用tt.call_me”。因为你是在主线程中,所以主线程进行了这个调用。Python并不会自动把这个调用转发到其他线程。

在run方法中的self.call_me这一行工作得很好。因为'run'方法就是线程,而它调用的任何东西都是在这个线程里执行的。

撰写回答