Added a threading lock to output

The continuous method failed randomly under testing and it turned out to
be a race condition on changing the output stream. A threading lock has
been added to ensure the output doesn't get switched out under the
encoder thread's nose and an attempt at flushing streams that we didn't
explicitly open has also been added so that the user can be reasonably
certain that once the encoder's wait() method returns, everything's
actually written to the stream.