繁体   English   中英

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

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

语境:

我有一个线程类,它在 for 循环中被调用 10 次。

对于类的每个对象,我为用户传入一个username ,该用户username由它在 for 循环中的位置决定,例如user0, user1, user2

我在类中创建了一个名为new_message()的方法,它只是打印另一条消息。

在类的def run()方法中,我将username作为键和new_message()函数作为值添加到字典中

我的问题:

我试图为其中一个用户调用new_message()函数,希望该函数可以在为该特定用户创建的线程中运行,但我认为它在主线程中运行,导致我的下一行代码等待。

所以我的问题是:

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


请注意,这是我遇到的一个更大问题的表示,但我制作了一个模仿我的代码的最小复制示例。

代码:

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')

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

不,这是不可能的。 您已经start() ed 线程,这使它运行它的run()方法。 您不能调用这样的方法来在该特定线程中运行它 - 它只会在您观察到的调用它的线程上运行(它在您的主线程中运行)。

您需要其他线程(我们称它们为工作线程)与外部提交的任务协作以实现此目的。 例如,您可以让工作线程在完成初始工作后监听工作队列,以获取任务(即函数)并运行它们。

这是对您的代码的快速实现:

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")

您会发现"This line shouldn't be waiting to print"现在确实不会等待。 主线程将其作为任务放在所选工作线程的队列中。 一旦完成了self.initialize()调用,工作人员就会拿起它。

暂无
暂无

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

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