context.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # coding: utf-8
  2. """zmq Context class"""
  3. # Copyright (C) PyZMQ Developers
  4. # Distributed under the terms of the Modified BSD License.
  5. from ._cffi import C, ffi
  6. from .constants import EINVAL, IO_THREADS, LINGER
  7. from zmq.error import ZMQError, InterruptedSystemCall, _check_rc
  8. class Context(object):
  9. _zmq_ctx = None
  10. _iothreads = None
  11. _closed = None
  12. _shadow = False
  13. def __init__(self, io_threads=1, shadow=None):
  14. if shadow:
  15. self._zmq_ctx = ffi.cast("void *", shadow)
  16. self._shadow = True
  17. else:
  18. self._shadow = False
  19. if not io_threads >= 0:
  20. raise ZMQError(EINVAL)
  21. self._zmq_ctx = C.zmq_ctx_new()
  22. if self._zmq_ctx == ffi.NULL:
  23. raise ZMQError(C.zmq_errno())
  24. if not shadow:
  25. C.zmq_ctx_set(self._zmq_ctx, IO_THREADS, io_threads)
  26. self._closed = False
  27. @property
  28. def underlying(self):
  29. """The address of the underlying libzmq context"""
  30. return int(ffi.cast('size_t', self._zmq_ctx))
  31. @property
  32. def closed(self):
  33. return self._closed
  34. def set(self, option, value):
  35. """set a context option
  36. see zmq_ctx_set
  37. """
  38. rc = C.zmq_ctx_set(self._zmq_ctx, option, value)
  39. _check_rc(rc)
  40. def get(self, option):
  41. """get context option
  42. see zmq_ctx_get
  43. """
  44. rc = C.zmq_ctx_get(self._zmq_ctx, option)
  45. _check_rc(rc)
  46. return rc
  47. def term(self):
  48. if self.closed:
  49. return
  50. rc = C.zmq_ctx_destroy(self._zmq_ctx)
  51. try:
  52. _check_rc(rc)
  53. except InterruptedSystemCall:
  54. # ignore interrupted term
  55. # see PEP 475 notes about close & EINTR for why
  56. pass
  57. self._zmq_ctx = None
  58. self._closed = True
  59. __all__ = ['Context']