Use an event loop library (libuv/libevent) instead of threads
mainBy default, the NATS library creates a dedicated thread for each connection to handle socket reads. To reduce thread overhead or integrate with existing event-driven architectures, you can use an event loop adapter (e.g., libuv or libevent).
Integration Steps
- Create your event loop instance (e.g.,
uv_default_loop()). - Use
natsOptions_SetEventLoop()to provide the loop and the necessary adapter functions (Attach, Read, Write, Detach). - Run your event loop.
Critical Warning: Publishing and Request-Reply
When using an event loop, publishing is asynchronous; data is placed in a buffer and sent when the event loop notifies the library that the socket is writable.
Do not call blocking or request-reply functions from the thread running the event loop, such as:
natsConnection_Request()natsConnection_Flush()natsConnection_FlushTimeout()
If you call these from the event loop thread, the data may never be sent because the loop is blocked, causing the calls to timeout. For natsConnection_Request(), use natsConnection_PublishRequest() and register a subscriber for the response instead.
// Example using libuv
uv_loop_t *uvLoop = uv_default_loop();
natsOptions_SetEventLoop(opts,
(void*) uvLoop,
natsLibuv_Attach,
natsLibuv_Read,
natsLibuv_Write,
natsLibuv_Detach);
natsConnection_Connect(&conn, opts);
natsConnection_Subscribe(&sub, conn, subj, onMsg, NULL);
uv_run(uvLoop, UV_RUN_DEFAULT);