Refactoring some generic thread management functionality under a new file thread.c

Signed-off-by: Olli Vanhoja <olli.vanhoja@gmail.com>