当前位置: 首页 > 面试题库 >

如何将数据发送到正在运行的python线程?

寇景明
2023-03-14
问题内容

我有一个在我的应用程序中的单独线程中运行的类。我可以一次运行多个线程,并且这些线程是守护程序。一段时间后, 其中一些
线程需要接收和处理消息。我该怎么做呢?

我的代码示例如下所示:

import threading
import time

class MyThread(threading.Thread):
    def __init__(self, args=(), kwargs=None):
        threading.Thread.__init__(self, args=(), kwargs=None)
        self.daemon = True
        self.receive_messages = args[0]

    def run(self):
        print threading.currentThread().getName(), self.receive_messages

    def do_thing_with_message(self, message):
        if self.receive_messages:
            print threading.currentThread().getName(), "Received %s".format(message)

if __name__ == '__main__':
    threads = []
    for t in range(10):
        threads.append( MyThread(args=(t % 2 == 0,)))
        threads[t].start()
        time.sleep(0.1)

    for t in threads:
        t.do_thing_with_message("Print this!")

输出:

Thread-1 True
Thread-2 False
Thread-3 True
Thread-4 False
Thread-5 True
Thread-6 False
Thread-7 True
Thread-8 False
Thread-9 True
Thread-10 False
MainThread Received %s
MainThread Received %s
MainThread Received %s
MainThread Received %s
MainThread Received %s

但是,我希望最后五行与无关MainThread,而不是%s,我希望对我来说Print this!像这样:

Thread-1 True
Thread-2 False
Thread-3 True
Thread-4 False
Thread-5 True
Thread-6 False
Thread-7 True
Thread-8 False
Thread-9 True
Thread-10 False
Thread-1 Received Print this!
Thread-3 Received Print this!
Thread-5 Received Print this!
Thread-7 Received Print this!
Thread-9 Received Print this!

我如何正确地向正在运行的线程发送这样的消息?

附录:

如果我在该块之后有这个块Print this!,并使用@dano的代码来解决上述问题,则它似乎没有响应这些新消息。

for t in threads:
    t.queue.put("Print this again!")
    time.sleep(0.1)

在这种情况下,我希望输出的结尾看起来像这样

Thread-1 Received Print this!
Thread-3 Received Print this!
Thread-5 Received Print this!
Thread-7 Received Print this!
Thread-9 Received Print this!
Thread-1 Received Print this again!
Thread-3 Received Print this again!
Thread-5 Received Print this again!
Thread-7 Received Print this again!
Thread-9 Received Print this again!

问题答案:

您可以使用Queue.Queue(或queue.Queue在Python 3中):

import threading
import time 
from Queue import Queue

print_lock = threading.Lock()

class MyThread(threading.Thread):
    def __init__(self, queue, args=(), kwargs=None):
        threading.Thread.__init__(self, args=(), kwargs=None)
        self.queue = queue
        self.daemon = True
        self.receive_messages = args[0]

    def run(self):
        print threading.currentThread().getName(), self.receive_messages
        val = self.queue.get()
        self.do_thing_with_message(val)

    def do_thing_with_message(self, message):
        if self.receive_messages:
            with print_lock:
                print threading.currentThread().getName(), "Received {}".format(message)

if __name__ == '__main__':
    threads = []
    for t in range(10):
        q = Queue()
        threads.append(MyThread(q, args=(t % 2 == 0,)))
        threads[t].start()
        time.sleep(0.1)

    for t in threads:
        t.queue.put("Print this!")

    for t in threads:
        t.join()

我们将Queue实例传递给每个线程,然后将消息发送给Threadusing
queue.put。我们等待消息到达run方法中,该方法Thread实际上是在单独的执行线程中运行的对象的一部分。收到消息后,我们将调用do_thing_with_message,它将在同一后台线程中运行。

我还向threading.Lock代码中添加了,以使打印到标准输出的图像不会混淆。

编辑:

如果您希望能够向线程传递多条消息,只需使用循环:

def run(self):
    print threading.currentThread().getName(), self.receive_messages
    while True:
        val = self.queue.get()
        if val is None:   # If you send `None`, the thread will exit.
            return
        self.do_thing_with_message(val)


 类似资料:
  • 假设我在服务中有一个可用的字符串test=“value”,并希望将其发送到我正在运行的mainactivity。如何安全地发送数据?我在寻找一个最简单的例子,其他应用程序看不到数据。当我看意图时,它会说: 广播是任何应用程序都可以接收的消息。系统为系统事件提供各种广播,例如当系统启动或设备开始充电时。您可以将广播发送到 但是,我只想将其发送到我的应用程序,因为它包含私人数据。在我的服务中,我尝试了

  • 问题内容: 我正在使用自定义信号处理程序在自定义Java守护程序中捕获TERM,ABRT和INT信号。我在代码中有此处理程序,以便可以向其发送TERM信号,并通过kill命令正常关闭程序。信号处理程序现在可以正常工作,但是当我编译代码时,我收到以下警告(很多次): 警告:sun.misc.SignalHandler是Sun专有的API,将来的发行版中可能会删除它。 在使用这些类时: 有没有更好的方

  • 我正在使用Hibernate。我有一把刀: 在哪里 并用@Entity注释。 它包含它所表示的表的所有列名。 然后,我的服务类自动连接了上述dao对象。我可以看到DmRequestDomain的值正确地打印在日志文件中。 但是当我通过这条道调用add时,我在我的服务器日志中看到所有的空值都被发送了。 可能的原因是什么。 我在服务器日志中看到的查询是

  • 问题内容: 我正在使用Flask创建一个网站,并且希望能够使用页面中的数据执行python代码。我知道我可以简单地使用表单,但是它是一个页面,它在接收用户输入时会不断更新,并且每次发生任何事情时都要重新加载页面,这是一个很大的麻烦。我知道我可以在javascript内执行操作,但是如何使用js变量在javascript内执行操作?到目前为止,我唯一能想到的就是用js更新外部数据库(如MongoDB

  • 我正在使用Python语言。我有csv文件,我需要转换成json并发送到kafka,然后发送到ElasticSearch。 我能够将Csv转换为Json并发送给Kafka消费者。如何从Kafka Consumer向ElasticSearch获取数据

  • 我正在尝试在我的网站上实现一个拖放文件上传器。文件被删除后立即上传,我想生成一个URL与flask将弹出在预览。我正在使用Dropzone.js。在dropzone的文档中,提供了一个示例,作为将数据从服务器发回并在文件上载后显示的指南。https://github.com/enyo/dropzone/wiki/faq#i-want-to-display-additution-informatio