{"id":31646644,"url":"https://github.com/hyperf/single-flight-incubator","last_synced_at":"2025-10-07T05:55:20.880Z","repository":{"id":299472714,"uuid":"1002954020","full_name":"hyperf/single-flight-incubator","owner":"hyperf","description":null,"archived":false,"fork":false,"pushed_at":"2025-09-23T09:29:12.000Z","size":97,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-23T09:29:14.328Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hyperf.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"open_collective":"hyperf","custom":"https://hyperf.wiki/#/zh-cn/donate"}},"created_at":"2025-06-16T11:56:18.000Z","updated_at":"2025-09-23T09:21:46.000Z","dependencies_parsed_at":"2025-09-23T09:20:59.980Z","dependency_job_id":"f414a76d-a537-4cdf-940f-fc90e49e6ab7","html_url":"https://github.com/hyperf/single-flight-incubator","commit_stats":null,"previous_names":["hyperf/single-flight-incubator"],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/hyperf/single-flight-incubator","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hyperf%2Fsingle-flight-incubator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hyperf%2Fsingle-flight-incubator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hyperf%2Fsingle-flight-incubator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hyperf%2Fsingle-flight-incubator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hyperf","download_url":"https://codeload.github.com/hyperf/single-flight-incubator/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hyperf%2Fsingle-flight-incubator/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":278728316,"owners_count":26035412,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-07T02:00:06.786Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-10-07T05:55:17.159Z","updated_at":"2025-10-07T05:55:20.875Z","avatar_url":"https://github.com/hyperf.png","language":"PHP","readme":"# Hyperf Concurrent Tools\n\n一个hyperf常用并发工具库，包括single-flight、barrier、semaphore、worker-pool\n\n## 安装\n\n```bash\ncomposer require hyperf/single-flight-incubtor\n```\n\n## 基本使用\n**所有例子都在[examples](examples)目录下，更多用法请参考[tests](tests)目录**\n### single-flight\n```php\n$ret = [];\n$barrierKey = uniqid();\n\nrun(static function () use (\u0026$ret, $barrierKey) {\n    for ($i = 0; $i \u003c 10; ++$i) {\n        go(static function () use (\u0026$ret, $barrierKey, $i) {\n            $ret[] = SingleFlight::do($barrierKey, static function () use ($i) {\n                // ensure that other coroutines can be scheduled at the same time\n                usleep(1000);\n                return [Coroutine::getCid() =\u003e $i];\n            });\n        });\n    }\n});\n\nif (count(array_unique($ret)) === 1) {\n    $ret = var_export($ret, true);\n    printf(\"%s\\n只有一个协程会执行闭包逻辑，其他协程等待其结果进行复用\\n\", $ret);\n}\n```\n\n### barrier\n```php\nrun(static function () {\n    $parties = 10;\n    $barrier = new CounterBarrier($parties);\n    $sleepMs = 5;\n\n    for ($i = 0; $i \u003c $parties - 1; ++$i) {\n        go(static function () use ($barrier) {\n            $waitAt = microtime(true);\n            $barrier-\u003eawait();\n            // your biz logic here\n            $resumeAt = microtime(true);\n            $elapsed = ($resumeAt - $waitAt) * 1000;\n            printf(\"协程 [%d] 等待 %.2f 毫秒后，恢复执行\\n\", Coroutine::getCid(), $elapsed);\n        });\n    }\n\n    go(static function () use ($barrier, $sleepMs) {\n        usleep($sleepMs * 1000);\n        printf(\"协程 [%d] 作为最后一个协程，等待 %d 毫秒后加入屏障，同其他协程一起执行\\n\", Coroutine::getCid(), $sleepMs);\n        $barrier-\u003eawait();\n        // your biz logic here\n    });\n});\n```\n\n### semaphore\n```php\nrun(static function () {\n    $sema = new Semaphore(3);\n\n    go(static function () use ($sema) {\n        $sleepSec = 1;\n        $tokens = 1;\n        defer(static function () use ($sema, $sleepSec, $tokens) {\n            printf(\"协程 [%d] 占用信号量 %d 秒后释放\\n\", Coroutine::getCid(), $sleepSec);\n            $sema-\u003erelease($tokens);\n        });\n\n        $acquireAt = time();\n        $sema-\u003eacquire($tokens);\n        $resumedAt = time();\n        $elapsed = $resumedAt - $acquireAt;\n        printf(\"协程 [%d] 于 %d 秒后获取信号量成功\\n\", Coroutine::getCid(), $elapsed);\n        sleep($sleepSec);\n    });\n\n    $chan = new Channel();\n    go(static function () use ($sema, $chan) {\n        $sleepSec = 2;\n        $tokens = 2;\n        defer(static function () use ($sema, $sleepSec, $tokens) {\n            printf(\"协程 [%d] 占用信号量 %d 秒后释放\\n\", Coroutine::getCid(), $sleepSec);\n            $sema-\u003erelease($tokens);\n        });\n\n        $acquireAt = microtime(true);\n        $sema-\u003eacquire($tokens);\n        // 唤醒下面一个协程\n        $chan-\u003eclose();\n        $resumedAt = microtime(true);\n        $elapsed = ($resumedAt - $acquireAt) * 1000;\n        printf(\"协程 [%d] 于 %d 秒后获取信号量成功\\n\", Coroutine::getCid(), $elapsed);\n        sleep($sleepSec);\n    });\n\n    go(static function () use ($sema, $chan) {\n        $tokens = 3;\n        defer(static function () use ($sema, $tokens) {\n            $sema-\u003erelease($tokens);\n            printf(\"协程 [%d] 释放信号量\\n\", Coroutine::getCid());\n        });\n\n        // 确保此协程在前一个协程后尝试获取信号量\n        $chan-\u003epop();\n        $acquireAt = time();\n        $sema-\u003eacquire($tokens);\n        $resumedAt = time();\n        $elapsed = $resumedAt - $acquireAt;\n        printf(\"协程 [%d] 于 %d 秒后获取信号量成功\\n\", Coroutine::getCid(), $elapsed);\n    });\n});\n```\n\n### worker-pool\n```php\nrun(static function () {\n    $config = new Config();\n    $config-\u003esetCapacity(5);\n    $pool = new WorkerPool($config);\n\n    // 关闭协程池\n    defer(static fn () =\u003e $pool-\u003estop());\n\n    // 投递异步任务\n    $mockBiz = static fn (): int =\u003e Coroutine::getCid();\n    $ret = $pool-\u003esubmit($mockBiz);\n    if (is_null($ret)) {\n        printf(\"投递异步任务若不关心返回值可直接忽略\\n\");\n    }\n\n    // 投递同步任务，可直接获取结果\n    $ret = $pool-\u003esubmit($mockBiz, sync: true);\n    if (Coroutine::getCid() !== $ret) {\n        printf(\"同步任务投递到worker-pool中的工作协程执行\\n\");\n    }\n\n    // 投递异步任务，通过waitResult方法获取结果\n    $task = new Task($mockBiz(...), sync: false);\n    $nullRet = $pool-\u003esubmitTask($task);\n    if (is_null($nullRet)) {\n        printf(\"投递异步任务不会直接得到返回值，可通过waitResult方法获取\\n\");\n    }\n    $ret = $task-\u003ewaitResult();\n    if (Coroutine::getCid() !== $ret) {\n        printf(\"异步任务投递到worker-pool中的工作协程执行\\n\");\n    }\n});\n```\n\n### double-barrier\n```php\nrun(static function () {\n    $barrier = new DoubleBarrier(3);\n\n    $queuedMs = 10;\n    $startAt = (int)floor(microtime(true) * 1000);\n    $biz = static function () use ($startAt, $queuedMs) {\n        $cid = Coroutine::getCid();\n        $elapsed = (int)floor(microtime(true) * 1000) - $startAt;\n        printf(\"协程 [%d] 等待 %d 毫秒后组队成功，同时执行\\n\", $cid, $elapsed);\n        if ($cid % 2) {\n            usleep($queuedMs * 1000);\n            printf(\"协程 [%d] 额外执行 %d 毫秒后，结束执行\\n\", $cid, $queuedMs);\n        } else {\n            printf(\"协程 [%d] 执行完毕，等待其他协程执行完毕，同时退出\\n\", $cid);\n        }\n    };\n\n    $exit = static function () use ($startAt) {\n        $cid = Coroutine::getCid();\n        $elapsed = (int)floor(microtime(true) * 1000) - $startAt;\n        printf(\"协程 [%d] 共执行 %d 毫秒，同时结束执行\\n\", $cid, $elapsed);\n    };\n\n    go(static function () use ($barrier, $biz, $exit) {\n        defer($exit(...));\n        $barrier-\u003eexecute($biz(...));\n    });\n    go(static function () use ($barrier, $biz, $exit) {\n        defer($exit(...));\n        $barrier-\u003eexecute($biz(...));\n    });\n    go(static function () use ($barrier, $biz, $queuedMs, $exit) {\n        defer($exit(...));\n        usleep($queuedMs * 1000);\n        $barrier-\u003eexecute($biz(...));\n    });\n});\n```","funding_links":["https://opencollective.com/hyperf","https://hyperf.wiki/#/zh-cn/donate"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhyperf%2Fsingle-flight-incubator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhyperf%2Fsingle-flight-incubator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhyperf%2Fsingle-flight-incubator/lists"}