Deadlock fixes

Includes game state cache.
This patch needs to be deeply tested.

It also adds a new compilation flag "-DDEBUG_LOCKORDER" to detect inconsistent lock orderings that can cause deadlocks.