Alternative sources of heat

This week the weather is heavily influenced by the season – the autumn leaves are all falling with a splat, and cool temperatures with the high humidity have me turning up thermostats again. But there are other additional heat sources, scripting for example…

I have been trying to automate some of the image conversion and compression optimization tasks. Sometimes this works; a few attempts have had very curious results. Trying to inoculate against problems had me bump up against a surprisingly challenging question: how do you create a unique temporary directory name which avoids race conditions in a multi-threading script running on multiple boxen using a cloud drive?

function tempDir( $parent = null )
{
    // Sanity tests
    if ( $parent === null ) {
        $parent = sys_get_temp_dir();
    }
    $parent = rtrim( $parent, '/' );
    if ( !is_dir($parent) || !is_writeable( $parent ) ) {
        throw new Exception( sprintf( 'Parent directory is not writable: %s', $parent ) );
    }
 
    // Create directory
    $killLoop = 0;
    do  {
        $directory = $parent . '/' . mt_rand();
        $success = @mkdir( $directory );
        ++$killLoop;
        if ( !$success && $killLoop > 1000 ) {
            throw new Exception( sprintf( 'Unique directory attempts greater than 1k: %s', $parent ) );
        }
    }
    while ( !$success );
 
    return $directory;
}

It looks a bit crude to me, but it seems to work. Each child on each box (which have different operating systems) creates its own local temporary file and so far no collisions. Not tested on windows yet.

Currently I have four laptops recursing 10 different directories to convert lossy images to lossless formats, and then not-quite-exhaustively optimize the images for storage. Which is resulting a bit of spare heat. I sort of wish I had a set of big old tower boxen to run this on, because the back bedroom could use a few more therms.