[Solved] Convert a process based program into a thread based version?


The general case depends on whether the threads are wholly independent of each other. If you go multi-threaded, you must ensure that any shared resource is accessed appropriate protection.

The code shown has a shared resource in the use of srand() and rand(). You will get different results in a multi-threaded process compared with those from multiple separate processes. Does this matter? If not, you may be able to let the threads run, but the C standard says the srand() and rand() functions don’t have to be thread-safe.

If it matters — and it probably does — you need to use a different PRNG (pseudo-random number generator) which allows you to have independent sequences (for example, POSIX nrand48() — there may well be better alternatives, especially if you use modern C++).

The use of getpid() won’t work well in a multi-threaded process either. Each thread will get the same value (because the threads are all part of the same process), so the threads won’t get independent sequences of random numbers for another reason.

5

solved Convert a process based program into a thread based version?