简体   繁体   中英

multithreaded generation of all numbers in range in random order

I am searching the best algorithm where M threads generate all numbers from given range (1 .. N), but in random order. Every number should be generated only once, and distribution (is that good term?) of resulting numbers should be as equal as possible (across the threads and inside of any given thread)

So, my first attempt is

  1. every thread has his number T (1..M)
  2. every thread holds a bitmap of N/M bites (to mark numbers already generated)
  3. every thread generates a random bit position P between 0 and N/M - 1. If given bit is set to 1, it is searching for the first 0 to the right (with wrapping), so we have O(N*N) complexity
  4. we are setting that bit to 1
  5. bit position is expanded to number - basically P*M + T

Algorithm is good enough in terms of memory (N bits) and maybe not so with O complexity (N*N if i am correct), but distribution doesn't seem to be very equal

So question here:

is there a better algorithm (in terms of memory use, complexity and, first of all, result distribution) ?

Expanded, Michael's suggestion is to use a linear-time algorithm, Fisher--Yates for example, to generate a uniform random permutation sequentially. Then you can assign random numbers to threads using a static partitioning scheme (eg, with k threads, thread i in [0..k-1] gets the elements from n*i/k inclusive to n*(i+1)/k exclusive), or you can "pop" from the permutation in parallel (eg, store the current length of the vector, then fetch&add -1 to obtain the index from which to take the next element, or just use a mutex).

If this is not an acceptable solution, then please specify precisely why that is the case and what you're doing with the random numbers afterward -- it is difficult to imagine a situation where the sequential processing would be prohibitively expensive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM