properly handle pthread termination

As suggested by Cedric.