简体   繁体   English

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

[英]Making a call to a thread object's method from the context of the thread

I'm trying to make a call to one of a thread object's methods from the context of the thread using the object's handle. 我试图使用对象的句柄从线程的上下文中调用线程对象的方法之一。 However, this isn't working and instead the call to the method is being made from the context of the main thread. 但是,这不起作用,而是从主线程的上下文进行了对该方法的调用。 Is there any way around this? 有没有办法解决?

Here's some example code: 这是一些示例代码:

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

What I'm looking for is a way to make tt.call_me() be from the context of the thread such that current_thread().ident returns the same ID as it does when its called from the thread's run method. 我正在寻找的是一种使tt.call_me()来自线程上下文的方法,使得current_thread().ident返回与从线程的run方法调用时返回的ID相同的ID。

Any ideas? 有任何想法吗?

Python class methods can be called from any thread. 可以从任何线程调用Python类方法。 That goes for the threading.Thread class too. 这也适用于threading.Thread类。 When you wrote: 当你写:

tt.call_me()

You were saying, "whatever thread happens to be running this code, please call tt.call_me". 您说的是,“无论运行此代码的是哪个线程,请致电tt.call_me”。 Since you were in main thread, the main thread made the call. 由于您在主线程中,因此主线程进行了调用。 Python doesn't automatically proxy the call to the thread. Python不会自动将调用代理到线程。

The self.call_me line in the run method worked just fine. run方法中的self.call_me行工作正常。 The 'run' method is the thread and anything it calls is in that thread. “运行”方法是线程,它调用的任何内容都在该线程中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM