[libsocialcache] Improve locking and database cleanup

This commit adds more locking around sensitive code areas, and also
ensures that each derived type is responsible for closing the database
at the appropriate time (depending on the threading being used).
Merge pull request #15 from chriadam/lock

[libsocialcache] Improve locking and database cleanup