php-lock / lock

Lock library to provide serialized execution of PHP code.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unit Test fails if I try to use parallel threads

reeperbahnause opened this issue · comments

The following PHPUnit test fails if I try to use parallel threads

I'm using php-lock version 2.1 on windows with php version 7.4.6

If I deactivate the $this->mutex->synchronized function by commenting out the function the test is executed without an error.
Does anyone have an idea whats wrong with my test case?

<?php
namespace Squeeze;

use Exception;
use malkusch\lock\mutex\FlockMutex;
use PHPUnit\Framework\TestCase;

class ThreadLockTest extends TestCase
{

    /**
     * @var FlockMutex
     */
    private $mutex;

    /**
     * @var resource
     */
    private $file;

    protected function setUp(): void
    {
        parent::setUp();

        $this->file = __DIR__ . DIRECTORY_SEPARATOR . 'flock';
        $this->mutex = new FlockMutex(fopen($this->file, 'w'), 1);
    }

    protected function tearDown(): void
    {
        unlink($this->file);

        parent::tearDown();
    }

    public function testThreadLock(): void
    {
        $syncFunction = function ($i) {
            try {
                require_once __DIR__ . '/../../../bootstrap/app.php';
                echo $i .' Running ' . PHP_EOL;
                return $this->mutex->synchronized(function () use ($i) : string {
                    sleep(1);
                    return $i .' Finished.' . PHP_EOL;
                });
            } catch (Exception $e) {
                return $e->getMessage() . PHP_EOL;
            }
        };

        $results = array();
        for ($i = 1; $i < 6; $i++) {
            $results[] = \parallel\run($syncFunction, array($i));
        }

        foreach ($results as $item) {
            echo $item->value();
        }
    }
}

Try creating the mutex inside $syncFunction.