wait for background thread before free()ing koptcontext

This should prevent freeing resources that are actually in use in
a background thread.
Merge pull request #1228 from hwhw/fix_koptcontext_free

wait for background thread before free()ing koptcontext