kingbes/thread

Thread

v0.0.1 2025-06-07 03:31 UTC

This package is auto-updated.

Last update: 2025-06-09 13:52:24 UTC


README

php Thread composer package

PHP 8.2+
FFI *
NTS true
Windows true

composer

composer require kingbes/thread

usage

use KingBes\Thread\Thread;

class A
{
    public function demo()
    {
        echo "is demo";
    }
}

$class_a = new A();
$a = 1;
// 实例化 线程类
$thread = new Thread();
var_dump("start");
// 执行任务1
$thread->spawn(function () use (&$a) {
    echo "spawned 1 start:" . date("Y-m-d H:i:s") . "\n";
    sleep(1);
    $a += 3;
    var_dump($a);
    echo "spawned 1 end:" . date("Y-m-d H:i:s") . "\n";
});
// 执行任务2
$thread->spawn(function () use (&$a) {
    echo "spawned 2 start:" . date("Y-m-d H:i:s") . "\n";
    sleep(9);
    echo "spawned 2 end:" . date("Y-m-d H:i:s") . "\n";
    $a += 2;
    var_dump($a);
});
// 执行任务3
$thread->spawn(function () use (&$a, $class_a) {
    echo "spawned 3 start:" . date("Y-m-d H:i:s") . "\n";
    sleep(5);
    $a--;
    echo "spawned 3 end:" . date("Y-m-d H:i:s") . "\n";
    $class_a->demo();
    echo "\n";
});
// 等待任务执行完毕
$thread->wait();
var_dump("res:" . $a);
var_dump("end");
string(5) "start"
spawned 1 start:2025-06-06 09:10:15
spawned 2 start:2025-06-06 09:10:15
spawned 3 start:2025-06-06 09:10:15
int(4)
spawned 1 end:2025-06-06 09:10:16
spawned 3 end:2025-06-06 09:10:20
is demo
spawned 2 end:2025-06-06 09:10:24
int(5)
string(5) "res:5"
string(3) "end"