Add unblock method for graceful shutdown #156
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I hit the following problem and saw it in the issues too (#146) : how do you gracefully shutdown the server ? There is effectively no way of breaking out of incoming_requests() other than receiving a client request.
Rust favors message passing. We can't kill threads or send them signals Unix style. We can only pass messages between threads via channels to tell them to shut down on their own (or with synchronization primitives such as condvar, or with shared memory under lock). After some research, it turns out the standard library does blocking IO (ie the accept method on TcpListener used by tiny-http). There really is no way to break out of it except with a client request (or on error). This is already dealt with by a previous commit by @moises-silva (cde7981) : on object destruction we briefly connect to the server to unblock the thread stuck on accept. (side note : for async IO look for mio)
But a for loop on incoming_requests it still blocking. It's not stuck on accept but inside the message queue waiting on condvar for new client requests. This commit adds a special request variant that says to unblock the loop and return no client request (since there is none we just want to shutdown). I slightly modified the message_queue API (ie the pop method now returns an Option), which is internal. There are no changes on the public side, ie on server, except the addition of the unblock method that effectively unblocks one thread stuck in incoming_requests (or recv).
Since there is no breaking change to the public API, all existing code work as previously. The addition of unblock() allows to implement graceful server shutdown by calling it from another thread. Hopefully the two tests added make its usage clear. Let me know what you think.