refine code using threading