栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您可以使用

Queue.Queue
(或
queue.Queue
在Python 3中):

import threadingimport time from Queue import Queueprint_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
实例传递给每个线程,然后将消息发送给
Thread
using
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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639545.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号