pthread_cancel was sometimes called once the thread had exited, resolve this by having the function wait to be canceled.