[issue40485] Provide an abstraction for a select-able Event

Faidon Liambotis report at bugs.python.org
Fri Apr 9 10:57:01 EDT 2021


Faidon Liambotis <paravoid at debian.org> added the comment:

Thanks so much for all the work on os.eventfd(), it's exciting to see it come to fruition.

An eventfd variant of Event (compatible with the threading & multiprocessing APIs) is now as simple as:

class Event:
    _ONE = (1).to_bytes(8, byteorder=sys.byteorder)

    def __init__(self):
        self._event_fd = os.eventfd(0, os.EFD_NONBLOCK)
        self._selector = selectors.DefaultSelector()
        self._selector.register(self._event_fd, selectors.EVENT_READ)

    def is_set(self):
        return self.wait(timeout=0)

    def set(self):
        try:
            os.write(self._event_fd, self._ONE)
        except BlockingIOError:
            pass

    def clear(self):
        try:
            os.read(self._event_fd, 8)
        except BlockingIOError:
            pass

    def wait(self, timeout=None):
        return bool(self._selector.select(timeout=timeout))

    def fileno(self):
        return self._event_fd

Given this now has a fileno() method, it is now possible to wait for the event as part of a broader selector, among other events (e.g. a file or socket becoming available to read or write).

I don't know where (or how) such a variant would fit into stdlib. It's simpler and more lightweight (less fds) than both threading's and multiprocessing's, and could be used from both threads and processes. I'd love some guidance here. (If a maintainer or anyone else reading this wants to use the above code in a PR, feel free -- no copyright claimed or expected for this trivial piece of code above)

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40485>
_______________________________________


More information about the Python-bugs-list mailing list