Monkeys in the Machine



Monkeys in the Machine

2 2


monkeys-in-the-machine

Monkeys typing Shakespeare ... asynchronously!

On Github ericmann / monkeys-in-the-machine

Monkeys in the Machine

Presented by Eric Mann / @ericmann

To be, or not to be ...

To be, or not to be, that is the question— Whether 'tis Nobler in the mind to suffer The Slings and Arrows of outrageous Fortune, Or to take Arms against a Sea of troubles, And by opposing end them?

Infinite Monkey Theorem

“For years there has been a theory that millions of monkeys typing at random on millions of typewriters would reproduce the entire works of Shakespeare. The Internet has proven this theory to be untrue.” For years, I thought it would be fun to try to solve the problem posed by the Infinite Monkey Theorem. The thing is ... I didn't quite know where to start.

Genetic Algorithms

  • Start with a known text of fixed length
  • Generate a random set of random "attempts"
  • Rank the "best" vs the "worst" attempts
  • Use the best attempts to create a new set
  • Lather, rinse, repeat

Monkeys v1

createRandomPopulation();

while ( bestFitness() !== 0 ) {
    breedNextGeneration();
}

println( 'done!' );

Monkeys v1 will overtax your machine

  • It's is single-threaded
  • The iterations above expand to a monolithic application of several thousand lines
  • Any other operation has to wait before it can do anything else

Parallel Programming

  • Start with a kernel - core functionality
  • Iterate, iterate, iterate

Monkeys v2

createRandomPopulation();

while ( bestFitness() !== 0 ) {
    breedNextGeneration();

    // Do something else perhaps?
}

println( 'done!' );

Monkeys v2

createRandomPopulation();

function breedMonkeys()
{
    selectParentsForNextGeneration();
    yield breedNextGeneration();
}

while ( bestFitness() !== 0 ) {
    breedMonkeys();

    // Do something else perhaps?
}

println( 'done!' );

Monkeys v2 will work… kinda

  • It's still single-threaded
  • With several thousand iterations, this will still take a long time
  • The solution isn't optimized for your hardware.

Parallel Programming

  • Start with a kernel - core functionality
  • Iterate, iterate, iterate
  • Not all iterations need to be synchronous

Monkeys v3

createRandomPopulation();

$collectors = [];
foreach( $threads as $thread ) {
    array_push( $colletors, runInThread( $thread, 'breedSome' ) );
}

$once = breedSome();

foreach( $threads as $thread ) {
    $once = array_merge( $once, $thread->result() );
}

println( 'done!' );

Monkeys v3 is the optimal solution

  • Can use all of the processing power of your machine
  • Doesn't block other operations
  • Completely clean global scope per thread

Walkthrough

Full code is available on GitHub

So What?

Practical Applications

  • "Big data" processing
  • File transcoding
  • Remote integrations
  • Map/Reduce or Remote/Slow

Thank You

Eric Mann / @ericmann / Tozny

Monkeys in the Machine Presented by Eric Mann / @ericmann