anhngml / aforge

Automatically exported from code.google.com/p/aforge
Other
0 stars 0 forks source link

GA: Donate thread-safety to chromosomes #266

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Hi.

This code contribution comes as a consequence of this forum thread: 
http://www.aforgenet.com/forum/viewtopic.php?f=2&t=2420

.NET System.Random class seems to be non-thread-safe (e.g. see 
http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx). Then, 
chromosomes having a "static Random" member are non-thread safe, as well. This 
is a problem when many populations evolve in multiple threads.

There are variuos solutions to this problem:
1) wrapping Random generator within a thread-safe class inherited from Random 
class;
2) avoiding to declare "static" the chromosome Random instance;
3) using  System.Security.Cryptography.RNGCryptoServiceProvider, a 
cryptographically-strong random generator.

All those solutions have some drawback.

1) Thread safety is achieved locking the static generator. Lock decreases 
performance. The more the contention in generating random numbers, the worse 
the performance.
2) The chromosomes for a population are often instantiated almost 
simoultaneously. Since Random() constructor takes the seed from current machine 
time, many chromosomes happen to have the same seed, which is definitely not 
good. One might think to use a further random generator just for the sake of 
generating seeds. Anyway, this would not grant to preserve statistical 
characterization of the overall generated numbers.
3) RNGCryptoServiceProvider is extremely slower than Random and just generate 
numbers between the 0..255 (GetBytes())and 1..255 (GetNonZeroBytes()) ranges.

I suggest to go for the first solution.

Find attached an implementation of ThreadSafeRandom class (thanks to Stephen 
Toub).

All static Random instances shared among chromosomes can be redefined of this 
type. Since it inherits from Random, no further changes are needed.

Please, consider me available for help in case of need.

Cheers,
Marcello.

Original issue reported on code.google.com by esposito...@gmail.com on 24 Nov 2011 at 2:47

Attachments:

GoogleCodeExporter commented 9 years ago

Original comment by andrew.k...@gmail.com on 28 Nov 2011 at 8:29

GoogleCodeExporter commented 9 years ago
Updated classed of AForge.Genetic and AForge.Math.Random namespaces to use new 
ThreadSafeRandom class, so random numbers generation in those classes becomes 
thread safe.

Committed in revision 1639-1641. Will be released in version 2.2.3.

Original comment by andrew.k...@gmail.com on 28 Nov 2011 at 9:18

GoogleCodeExporter commented 9 years ago

Original comment by andrew.k...@gmail.com on 12 Dec 2011 at 9:17