Fix deadlock in multithreading.

Fixes #5971.
Merge pull request #5979 from unknownbrackets/multithread

Fix deadlock in multithreading