executor.pyx 968 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import asyncio
  2. from folly.executor cimport cAsyncioExecutor
  3. from libcpp.memory cimport make_unique, unique_ptr
  4. from cython.operator cimport dereference as deref
  5. from weakref import WeakKeyDictionary
  6. # asyncio Loops to AsyncioExecutor
  7. loop_to_q = WeakKeyDictionary()
  8. cdef class AsyncioExecutor:
  9. def __cinit__(self):
  10. self.cQ = make_unique[cAsyncioExecutor]()
  11. def fileno(AsyncioExecutor self):
  12. return deref(self.cQ).fileno()
  13. def drive(AsyncioExecutor self):
  14. deref(self.cQ).drive()
  15. def __dealloc__(AsyncioExecutor self):
  16. # We drive it one last time
  17. deref(self.cQ).drive()
  18. cdef cAsyncioExecutor* get_executor():
  19. try:
  20. loop = asyncio.get_event_loop()
  21. except RuntimeError:
  22. return NULL
  23. try:
  24. Q = <AsyncioExecutor>(loop_to_q[loop])
  25. except KeyError:
  26. Q = AsyncioExecutor()
  27. loop.add_reader(Q.fileno(), Q.drive)
  28. loop_to_q[loop] = Q
  29. return Q.cQ.get()