Add a lock for folks using threading. Mucho helpful.

I can't see any *downside* to including a lock here. Basically, it
just says that two threads running in parallel can't touch the code
between the lock.acquire() <--> lock.release() statements
concurrently. We use it in low-level util functions to prevent
concurrent file reads/writes.

This was a bug that showed up while running our auto-documentation
examples.
utility functions should be a simple a possible, just split all this up for simplicity.