上下文:
我有一个线程类,在for循环中被调用10次。
对于该类的每个对象,我为用户传递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')
答案 0 :(得分:1)
是否可以调用类对象线程的方法并使它在该特定线程中运行?
否,这是不可能的。您已经start()
编辑了线程,这使其运行其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()
调用,工作人员就会接听。