mattgodbolt / seasocks

Simple, small, C++ embeddable webserver with WebSockets support
BSD 2-Clause "Simplified" License
734 stars 120 forks source link

Why does this API so strictly enforce thread management? #155

Open bw-work-mt opened 3 years ago

bw-work-mt commented 3 years ago

Does anyone know why this API enforces all messages must originate from the same thread the server was started on?

hoytech commented 3 years ago

Seasocks is an asynchronous server, using the linux-specific epoll() API. There is one thread responsible for managing all events, like reading from the socket, buffering messages, writing to the socket, etc.

If multiple threads could all interact with the socket, then there would need to be locking to protect the data-structures this thread uses, which would increase complexity and decrease performance.

But this typically isn't a problem, since actually sending/receiving messages takes so little resources. Usually it's your own code that you want to run in a separate thread anyway. What you can do is create a worker thread pool that takes requests off a queue. The workers will then do their expensive processing, and push the responses onto another queue, and then wake up the seasocks thread to send the messages.

You can also have multiple processes all accepting connections from the same websocket if you use SO_REUSEPORT.