Acme-SexualReproduction

 view release on metacpan or  search on metacpan

README  view on Meta::CPAN

Acme-SexualReproduction

Acme::SexualReproduction is a great way to improve a program kind's
survivability by mixing the genes of processes creating a child one.

INSTALLATION

To install this module, run the following commands:

	perl Build.PL
	./Build
	./Build test
	./Build install

lib/Acme/SexualReproduction.pm  view on Meta::CPAN


Version 0.01

=cut

our $VERSION = '0.01';


=head1 SYNOPSIS

This module allows you to improve the chances of your program kind to survive by mixing genes of their processes when creating a child process. Especially if your program is a K-strategic one.

In a "female" process:

    use Acme::SexualReproduction 'female';
    my $pid = female('unique ID', \%chromosomes);
    ...

In a "male" process:

    use Acme::SexualReproduction 'male';
    male('unique ID', \%chromosomes);

The child is spawned then from the female process.

=head1 EXPORT

Only two functions are exported: one for insemination (a "male" process) and one for allocating a shared hash of chromosomes and spawning a child (a "female" process).

=head2 male($id, \%chromosomes);

Tries to write the chromosomes to the shared memory of the female process with unique SHM $id. Sadly, does not return the child's PID.

=cut

=for comment
This subroutine was written first just because it was easier. I strongly disclaim any sexual discrimination from my side. It's written just for fun anyways.
=cut

sub male {
	my ($id, $chromosomes) = @_;
	croak "\$chromosomes must be a HASH reference" unless ref $chromosomes eq 'HASH';
	croak "Male process is sterile" unless keys %$chromosomes;
	tie my $sperm, 'IPC::Shareable', { key => $id } || croak "Couldn't copulate with female process, SHM ID $id: $!";
	(tied $sperm)->shlock;
	@{$sperm}{keys %$chromosomes} = values %$chromosomes;
	(tied $sperm)->shunlock;
	return 1;
}

=head2 $pid = female($id, \%chromosomes)

Shares a hash for the male process' chromosomes, waits for the insemination, mixes the genes and spawns the child process. \%chromosomes hash reference is changed in the child process.

=cut

sub female {	
	my ($id, $chromosomes) = @_;
	croak "\$chromosomes must be a HASH reference" unless ref $chromosomes eq 'HASH';
	tie my $sperm, 'IPC::Shareable', {key => $id, create => 1 } or carp("Couldn't copulate with male process: $!"), return;
	sleep 0.5 while !keys %$sperm; # foreplay
	keys %$sperm eq keys %$chromosomes or carp("Chromosome mismatch"), return;
	my %child_chromosomes = map { $_, int rand 2 ? $chromosomes->{$_} : $sperm->{$_} } keys %$chromosomes;
	my $pid = fork;
	carp("Couldn't spawn a child: $!"), return unless defined $pid;
	%$chromosomes = %child_chromosomes if $pid == 0;
	return $pid;
}

=head1 AUTHOR



( run in 0.274 second using v1.01-cache-2.11-cpan-8d75d55dd25 )