Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unit Test fails if I try to use parallel threads #37

Open
reeperbahnause opened this issue Jul 10, 2020 · 1 comment
Open

Unit Test fails if I try to use parallel threads #37

reeperbahnause opened this issue Jul 10, 2020 · 1 comment

Comments

@reeperbahnause
Copy link

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();
        }
    }
}
@reeperbahnause reeperbahnause changed the title Unit Tests fails if I try to use parallel threads Unit Test fails if I try to use parallel threads Jul 10, 2020
@willemstuursma
Copy link
Contributor

Try creating the mutex inside $syncFunction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants