Making code multithread safe