Cleaned up threading util to avoid race conditions also in environments capable of running multiple threads simultaneously