“Why doesn’t format simply do its job and print immediately?” - Redditor

Many programmers new to Lisp have been baffled when they use (format) to write to *STANDARD-OUTPUT* and the text appears after inexplicable delays or output from multiple threads appear out of sequence.

The reason is that *STANDARD-OUTPUT* is a buffered stream by default. Text written to such a stream is buffered until an event occurs which triggers the process of actually writing to the output. The usual trigger events are:

  • the buffer is full,
  • the buffer is closed, or
  • a #\NEWLINE is written.

There are two options to print the buffer’s content immediately without otherwise interfering with the stream: (finish-output) and (force-output).

(finish-output) is a blocking function. It ensures that all buffered output is written to the output stream before returning.

(force-output) is a non-blocking function. It initiates the writing process and then returns immediately without waiting for the buffer to be completely written.

A code example:

(format t "Debug a value: ~A" 5)
(finish-output)