Replaced rand() with rand_r() in order to guarantee thread safety