Multiplex on queue.Queue?

后端 未结 4 2030
感情败类
感情败类 2021-02-13 22:19

How can I go about \"selecting\" on multiple queue.Queue\'s simultaneously?

Golang has the desired feature with its channels:

select {
case i1 = <-c1:         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-13 22:48

    The pychan project duplicates Go channels in Python, including multiplexing. It implements the same algorithm as Go, so it meets all of your desired properties:

    • Multiple producers and consumers can communicate through a Chan. When both a producer and consumer are ready, the pair of them will block
    • Producers and consumers are serviced in the order they arrived (FIFO)
    • An empty (full) queue will block consumers (producers).

    Here's what your example would look like:

    c1 = Chan(); c2 = Chan(); c3 = Chan()
    
    try:
        chan, value = chanselect([c1, c3], [(c2, i2)])
        if chan == c1:
            print("Received %r from c1" % value)
        elif chan == c2:
            print("Sent %r to c2" % i2)
        else:  # c3
            print("Received %r from c3" % value)
    except ChanClosed as ex:
        if ex.which == c3:
            print("c3 is closed")
        else:
            raise
    

    (Full disclosure: I wrote this library)

提交回复
热议问题