简体   繁体   English

有没有办法调用类对象线程的方法并让它在该特定线程中运行?

[英]Is there a way to call a method of a class object thread and have it run in that specific thread?

Context:语境:

I have a threading class, which is called 10 times in a for loop.我有一个线程类,它在 for 循环中被调用 10 次。

For each object of the class, I pass in a username for the user which is determined by its place in the for loop, eg user0, user1, user2 ect.对于类的每个对象,我为用户传入一个username ,该用户username由它在 for 循环中的位置决定,例如user0, user1, user2

I created a method called new_message() in the class, which just prints another message.我在类中创建了一个名为new_message()的方法,它只是打印另一条消息。

In the def run() method of the class, I added the username as key and the new_message() function as the value into a dictionary在类的def run()方法中,我将username作为键和new_message()函数作为值添加到字典中

My Problem:我的问题:

I tried to call the new_message() function for one of the users, and that hopelfully the function would run in thread created for that specific user, but instead I think it ran in the main thread, causing my next lines of code to wait.我试图为其中一个用户调用new_message()函数,希望该函数可以在为该特定用户创建的线程中运行,但我认为它在主线程中运行,导致我的下一行代码等待。

So my question is:所以我的问题是:

Is there a way to call a method of a class object thread and have it run in that specific thread?有没有办法调用类对象线程的方法并让它在该特定线程中运行?


Do note this is representation of a larger problem I have, but I have made a minimal reproduced example which mimics my code.请注意,这是我遇到的一个更大问题的表示,但我制作了一个模仿我的代码的最小复制示例。

Code:代码:

import time

import threading

dict = {

}

class go(threading.Thread):
    def __init__(self, username):
        threading.Thread.__init__(self)
        self.username = username

    def run(self):
        dict[self.username] = self.new_message
        for count in range(10):
            print('Hello: '+self.username+'\n')
            time.sleep(10)

    def new_message(self):
        for count in range(10):
            print('How are you: '+self.username)
            time.sleep(2)


for count in range(10):
    username = ('user' + str(count))
    go(username).start()


what_user = input('What user')
dict[what_user]()

Print('This line shouldn't be waiting to print')

Is there a way to call a method of a class object thread and have it run in that specific thread?有没有办法调用类对象线程的方法并让它在该特定线程中运行?

No this is not possible.不,这是不可能的。 You have already start() ed the thread, which makes it run its run() method.您已经start() ed 线程,这使它运行它的run()方法。 You cannot call a method like that to run it in that specific thread -- it'll simply run on the thread that called it as you observed (it ran in your main thread).您不能调用这样的方法来在该特定线程中运行它 - 它只会在您观察到的调用它的线程上运行(它在您的主线程中运行)。

You need the other threads (let's call them worker threads) to be cooperative to externally submitted tasks to make this happen.您需要其他线程(我们称它们为工作线程)与外部提交的任务协作以实现此目的。 For instance, you may make the worker threads listen to a work queue after doing the initial work, to pick up tasks (ie functions) and run them.例如,您可以让工作线程在完成初始工作后监听工作队列,以获取任务(即函数)并运行它们。

Here is a quick implementation on your code:这是对您的代码的快速实现:

import time

import threading
from queue import Queue

dict = {}


class Go(threading.Thread):
    def __init__(self, username, work_queue):
        threading.Thread.__init__(self)
        self.username = username
        self.work_queue = work_queue

    def run(self):
        self.initialize()
        while True:
            task = self.work_queue.get()
            task()
            self.work_queue.task_done()

    def initialize(self):
        dict[self.username] = {"func": self.new_message, "queue": self.work_queue}
        for _ in range(10):
            print("Hello: " + self.username + "\n")
            time.sleep(10)

    def new_message(self):
        for _ in range(10):
            print("How are you: " + self.username)
            time.sleep(2)


for count in range(10):
    username = "user" + str(count)
    Go(username, Queue()).start()


what_user = input("What user")
selection = dict[what_user]
queue, method = selection["queue"], selection["func"]
queue.put(method)

print("This line shouldn't be waiting to print")

You'll observe that the "This line shouldn't be waiting to print" indeed won't wait now.您会发现"This line shouldn't be waiting to print"现在确实不会等待。 Main thread puts it as a task on the queue for the chosen worker thread.主线程将其作为任务放在所选工作线程的队列中。 The worker picks that up once it's done with its self.initialize() call.一旦完成了self.initialize()调用,工作人员就会拿起它。

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

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