wait for background thread before free()ing koptcontext

This should prevent freeing resources that are actually in use in
a background thread. See #1224 for a manifestation of that bug.