[galib] MultiThread + Functor

Glenn Sugden headcrash at mac.com
Fri May 21 01:36:30 EDT 2010


	I did it (a threaded version) without touching the GALib itself .. it was a bit hacky .. but I just didn't want to touch the library in case there were updates later on (I just don't have time to fold .diffs back in).

	Anyway, in a nutshell (this is copy, massaged, and pasted code, so YMMV):

	1) I get ahold of the GA's GAPopulation:
		GAPopulation pop = const_cast< GAPopulation* > ( ga->population() );

	2) I subvert the evaluator with my own:
		pop->evaluator( MyEvaluator );

	3) Then in my Evaluator:
		extern void MyEvaluator( GAPopulation & p )

	4) I launch some threads for each individual:
		for ( int i = 0; i < p.size(); i++ )
			parameters->individual = &p.individual( i );
			int rc = pthread_create( &task_threads[i], &attr, thread_function, parameters );

	5) And in my thread:
		static void *thread_function( void *parameters )

	6) I evaluate the individual:
		parameters->individual->evaluate();

	7) Then when all of the threads are complete, I pull out the best genome from the population (just so I can display the progress so far):
		GARealGenome *best_genome = (GARealGenome*)&p.individual(0);
		double best_score = best_genome->score();
		for ( int i = 1; i < p.size(); i++ )
		        GARealGenome* genome = (GARealGenome*)&p.individual(i);
			if ( genome->score() > best_score )
				best_genome_index = i;
			        best_genome = genome;
			        best_score = genome->score();

	8) All of the other magic happens in the outer shell (e.g. ga->step(), ga->statistics().bestIndividual(), etc.)

	
	Let me know if you can use some help if you decide to implement it this way. I think it's the best way to keep the GALib pristine and get the (multi-threaded) job done! ;-)

::Glenn



More information about the galib mailing list