Thread-Safe ZeroMQ
Thread-safe wrapper for ZeroMQ sockets.
The Problem
ZeroMQ sockets are not thread-safe. From the ZMQ Guide:
"Do not use or close sockets except in the thread that created them."
If you have a multi-threaded server where workers need to send through a shared socket, you'll get SIGSEGV crashes. Common workarounds like mutexes or proxies have significant overhead.
This library wraps ZMQ sockets in a dedicated thread and exposes channel handles that are Send + Sync.
Thread-safe ZeroMQ wrapper for multi-threaded servers.
Trade-off: ~9x latency overhead per message, but enables parallel sending from multiple threads - which can result in higher total throughput than single-threaded raw ZMQ.
Installation
[]
= "2.0"
# For async support
= { = "2.0", = ["async"] }
Requires ZeroMQ on your system:
# macOS
# Ubuntu/Debian
Or use Nix: just install-nix && just shell
Usage
Server with worker threads:
use ChannelPairBuilder;
use bounded;
use Arc;
use thread;
let ctx = new;
let socket = ctx.socket?;
socket.bind?;
let channel = new
.with_bounded_queue
.build?;
// Work queue for distributing messages to workers
let = bounded;
// Spawn workers - each can send responses through the shared channel
for _ in 0..4
// Main loop receives and dispatches to workers
loop
Async
use AsyncChannelPair;
let channel = new?;
channel.send.await?;
let response = channel.recv.await?;
channel.shutdown.await;
Examples
See the example/ directory for a complete fibonacci server/client:
Benchmarks
Compares ChannelPair against raw ZMQ with mutex and proxy patterns.
License
Apache-2.0