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.