fixing race condition in multithreaded solution