c# - Random number generator only generating one random number -
i have following function:
//function random number public static int randomnumber(int min, int max) { random random = new random(); return random.next(min, max); }
how call it:
byte[] mac = new byte[6]; (int x = 0; x < 6; ++x) mac[x] = (byte)(misc.randomnumber((int)0xffff, (int)0xffffff) % 256);
if step loop debugger during runtime different values (which want). however, if put breakpoint 2 lines below code, members of "mac" array have equal value.
why happen?
every time new random()
initialized using clock. means in tight loop same value lots of times. should keep single random
instance , keep using next
on same instance.
//function random number private static readonly random random = new random(); private static readonly object synclock = new object(); public static int randomnumber(int min, int max) { lock(synclock) { // synchronize return random.next(min, max); } }
edit (see comments): why need lock
here?
basically, next
going change internal state of random
instance. if @ same time multiple threads, could argue "we've made outcome more random", actually doing potentially breaking internal implementation, , start getting same numbers different threads, might problem - , might not. guarantee of happens internally bigger issue, though; since random
not make guarantees of thread-safety. there 2 valid approaches:
- synchronize don't access @ same time different threads
- use different
random
instances per thread
either can fine; mutexing single instance multiple callers @ same time asking trouble.
the lock
achieves first (and simpler) of these approaches; however, approach might be:
private static readonly threadlocal<random> apprandom = new threadlocal<random>(() => new random());
this per-thread, don't need synchronize.
Comments
Post a Comment