Fix a crash happening rarely when exiting serverd

The reason was that even though we were keeping mutexes locked, a thread that
had already opened the database wouldn't be stopped from reading or writing to
it. But all DB-related structures would have been freed by us, so it would
crash.
Keep mutex locked when exiting.
Merge pull request #711 from jimis/3.3.x

Fix a crash happening rarely when exiting serverd