• python中poolable queue


    在python cookbook中看见这么一段代码
    import queue
    import socket
    import os

    class PollableQueue(queue.Queue):
    def init(self):
    super().init()
    # Create a pair of connected sockets
    if os.name == 'posix':
    self._putsocket, self._getsocket = socket.socketpair()
    else:
    # Compatibility on non-POSIX systems
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('127.0.0.1', 0))
    server.listen(1)
    self._putsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self._putsocket.connect(server.getsockname())
    self._getsocket, _ = server.accept()
    server.close()

    def fileno(self):
        return self._getsocket.fileno()
    
    def put(self, item):
        super().put(item)
        self._putsocket.send(b'x')
    
    def get(self):
        self._getsocket.recv(1)
        return super().get()
    

    一开始不明白为什么实现了poolable,原来select函数的参数是3个列表,包含整数文件描述符,或者带有可返回文件描述符的fileno()方法对象。

    原来只需要支持fileno方法就可以给select调用了。

    客户端代码:
    import select
    import threading

    def consumer(queues):
    '''
    Consumer that reads data on multiple queues simultaneously
    '''
    while True:
    can_read, _, _ = select.select(queues,[],[])
    for r in can_read:
    item = r.get()
    print('Got:', item)

    q1 = PollableQueue()
    q2 = PollableQueue()
    q3 = PollableQueue()
    t = threading.Thread(target=consumer, args=([q1,q2,q3],))
    t.daemon = True
    t.start()

    Feed data to the queues

    q1.put(1)
    q2.put(10)
    q3.put('hello')
    q2.put(15)

  • 相关阅读:
    闽江学院2015-2016学年下学期《软件测试》课程-第五次博客作业
    在Swift中应用Grand Central Dispatch(下)
    在Swift中应用Grand Central Dispatch(上)转载自的goldenfiredo001的博客
    Asp.net mvc 框架揭秘之Asp.net +Mvc简介
    JavaScript数组
    网页校验
    删除弹出提示框_MVC
    业务体会
    判断数组值是否有重复
    sql
  • 原文地址:https://www.cnblogs.com/encode/p/6347335.html
Copyright © 2020-2023  润新知