Fixes for race conditions and volatility of vars in multithreading