c++ - cpzmq : Is it possible to get a global context without creating one as a global variable?

标签 c++ zeromq

我的用例通常只涉及一个全局上下文。 AFAIK,pyzmq 有一个 API zmq.Context.instance() 来获取全局单例,但我找不到等效的 cppzmq API。

是否可以访问全局上下文而无需显式创建并跟踪它?

最佳答案

Q : Is it possible to have access to a global context without having to create it explicitly and track it?

不,至少在不对当前cppzmq进行主要重新设计工作的情况下

原因:

PyZMQ 最近开始与用于使用已发布的通用 ZeroMQ API 的普通 Python 语言绑定(bind)不同

More Than Just Bindings

PyZMQ is ostensibly the Python bindings for ØMQ, but the project, following Python’s ‘batteries included’ philosophy, provides more than just Python methods and objects for calling into the ØMQ C++ library. The Core as Bindings

PyZMQ is currently broken up into four subpackages. First, is the Core. zmq.core contains the actual bindings for ZeroMQ, and no extended functionality beyond the very basic. The core modules are split, such that each basic ZeroMQ object (or function, if no object is associated) is a separate module, e.g. zmq.core.context contains the Context object, zmq.core.poll contains a Poller object, as well as the select() function, etc. ZMQ constants are, for convenience, all kept together in zmq.core.constants.

There are two reasons for breaking the core into submodules: recompilation and derivative projects. The monolithic PyZMQ became quite tedious to have to recompile everything for a small change to a single object. With separate files, that’s no longer necessary. The second reason has to do with Cython. PyZMQ is written in Cython, a tool for efficiently writing C-extensions for Python. By separating out our objects into individual pyx files, each with their declarations in a pxd header, other projects can write extensions in Cython and call directly to ZeroMQ at the C-level without the penalty of going through our Python objects.

Thread Safety

In ØMQ, Contexts are threadsafe objects, but Sockets are not. It is safe to use a single Context (e.g. via zmq.Context.instance()) in your entire multithreaded application, but you should create sockets on a per-thread basis. If you share sockets across threads, you are likely to encounter uncatchable c-level crashes of your application unless you use judicious application of threading.Lock, but this approach is not recommended.

努力工作的 ZeroMQ 极客已经注意到,原始的 ZeroMQ API(从 v2.1.11+ 开始)还有其他建议:

1) 应用必须显式创建至少一个Context实例(并稍后终止它)

2) Context - 实例可以在线程之间自由共享,无需Context 上需要任何锁定-服务调用方

3) 即使将 Socket 实例传递(而不是迁移)到新创建的线程(即由不属于“外部”的线程维护),也可以保证线程安全 -Context ),PyZMQ 文档明确警告并分散用户的注意力。

关于c++ - cpzmq : Is it possible to get a global context without creating one as a global variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58638564/

相关文章:

C++ 使用 lambda 函数作为模板函数特化

c++ - 设计模式、多代理系统、机器人

C++ 动态构造函数

node.js - 我应该如何处理同一主机上同一端口上的多个发布者?

zeromq - 在ZeroMQ队列中检测已丢弃的消息

java - 如何使用JZMQ处理错误?

c++ - 奇怪的返回值

c++ - 在 OSX 上使用 CMake 构建 Unity native 包

c++ - ZeroMQ 简单代理

python - zeromq (zmq) 缺少带有 c++ 发布者和 python 订阅者的消息