Fix a bug where pthread exit might get called twice due to a race condition, and later on crashing in _free().
Add a test for previous bug fix.