Refactor (and fix) thread.h