rand() with multiple threads

c, multithreading

Solution

To give you a short and straight answer:

`rand()` is not thread safe.

It should not be called from multiple threads without explicit critical section.

Problem

I was working on two threads trying to generate random numbers seeding once seed(time(null)) in main(). Program got segmentation fault continuously until I figured out that when working with threads we must generate random numbers for all threads in their own routines and there was no seg fault then. I tried to find answer on google as to why do we have to seed independently for all threads but did not find enough convincing answers. Could anyone please explain? Thanks!!

Original source

Related problems