Move threading code to its own module