Fix concurrency bug on handling output.
Use native join functions to wait termination of threads.