Fix some bugs in threading routines.
Fix some bugs in threading routines.

Plus refactoring flush -> _thread_flush. And solving possible race
conditions while sending files by opening files and providing file type
object instead.

tlamer/teres,tlamer/teres