I've always had a time understanding a particular aspect of continuations. I understand the basic concept - that you can invoke a continuation to transfer control to the place where you saved the continuation.
For simple examples, like REPL statements, this seems pretty simple (using Scheme as an example):
(+ 5 (call-with-current-continuation
(lambda (k) (+ 45 (k 4)))))
will return 9, since the (+ 45 __)
computation is simply lost and the call to k "plugs" 4 into (+ 5 _)
.
But continuations are often used in more complicated projects, especially web application servers. In this particular context, let's say you save a continuation c
while processing a user request. The web server then moves on to processing the next request until control is passed back to c
.
But after c
is invoked, the entire stack in place at the time c
was created will pop back into existence. What happens once that particular request handler is done? Does control simply return back to the main request processing portion of the application?
For example, let's say the outer loop is processing a buffer of requests from the client. If we save a continuation while processing one of these requests and then invoke that continuation after the buffer has been fully processed, won't that cause control and the stack to return back to the point where that request was handled, causing requests to be processed multiple times?