【发布时间】:2020-10-13 17:55:26
【问题描述】:
上下文:
我有一个线程类,在一个 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')
【问题讨论】:
标签: python multithreading dictionary oop python-multithreading