Use C++11 thread routines instead of pthread.

Also fix a dead lock caused by the refactor.