1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How can I wait for a threading event and socket pollin at the same time?

Discussão em 'Python' iniciado por Stack, Setembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    I have a select.poll() object for incoming messages of a socket, and a queue.Queue() object that contains potential outgoing messages.

    While both objects separately support waiting for a timeout without spending CPU cycles, I need to wait on both at the same time and resume the thread once either of them triggers. Is there a mechanism for that?

    I have tried waiting on both after another in a loop with very short timeout, but this is basically busy-waiting and ended up costing too much CPU. I have also tried increasing the timeout, which frees up CPU as expected but increases latency too much.

    It looks like select.poll() can wait on any UNIX file descriptor, so perhaps another way of asking my question is whether there is a queue.Queue() or threading.Event() alternative that exposes a file descriptor that can be polled?

    Current

    import socket
    import select
    import queue
    import threading

    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.connect(('localhost', 4200))
    incoming = select.poll()
    incoming.register(socket, select.POLLIN)

    outgoing = queue.Queue()

    while True:
    if incoming.poll(timeout=0.001):
    read(socket)
    try:
    msg = outgoing.get(block=False, timeout=0.001)
    send(socket, msg)
    except queue.Empty:
    pass


    Desired

    import socket
    import queue
    import threading

    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.connect(('localhost', 4200))
    outgoing = queue.Queue()

    poller = HYBRID_POLLER() # TODO
    poller.register(socket)
    poller.register(outgoing)

    while True:
    available = poller.poll(timeout=1)
    if socket in available:
    read(socket)
    if outgoing in available:
    msg = outgoing.get(block=False, timeout=0.001)
    send(socket, msg)

    Continue reading...

Compartilhe esta Página