Add locking primitives for concurrency; add rudimentary test; fix file handle leak