fix threading bugs

Fix locking of data structures shared across threads.