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

2024-04-23 22:07:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用对象的句柄从线程的上下文中调用一个thread对象的方法。但是,这不起作用,而是从主线程的上下文中调用方法。有什么办法吗?在

下面是一些示例代码:

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。在

有什么想法吗?在


Tags: 方法selfdefcurrentcall线程threadme
1条回答
网友
1楼 · 发布于 2024-04-23 22:07:17

Python类方法可以从任何线程调用。那是为了线程。线程我也是。当你写下:

tt.call_me()

你是说,“不管哪个线程运行这个代码,请调用打电话给我". 因为你在主线程中,所以主线程发出了调用。Python不会自动代理对线程的调用。在

在自我。打电话给我line-in-run方法工作得很好。“run”方法是线程,它调用的任何东西都在该线程中。在

相关问题 更多 >