欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > php fiber 应用

php fiber 应用

2025/5/22 22:59:54 来源:https://blog.csdn.net/lsswear/article/details/148031285  浏览:    关键词:php fiber 应用

参考

基于 PHP Fiber(纤程)的游戏开发分析-腾讯云开发者社区-腾讯云PHP 8.1 引入的 Fibers 为游戏开发带来新机遇,能管理渲染、物理计算等任务且不阻塞主线程。它支持并发,提升效率,简单易用,但也有局限,如单线程本质、上下文切换开销、调试复杂及生态系统不成熟。https://cloud.tencent.com/developer/article/2509749说明

  • 多个用户参与游戏
  • 每个人猜各自的最终数字
  • 每人做多猜五次

代码:

function getroundnum() {$num = rand(0, 30);return $num;
}
class Persion {public function __construct(public string $name) {}
}
class GuessNum extends Persion {private int $resultnum;public bool $result;private int $num;private int $type;public function __construct(public string $name, public int $gap = 1) {$this->num = getroundnum();$this->resultnum = getroundnum();$this->result = false;}//type 1加数字 2减数字private function getnextnum() {if ($this->num === 0) {return $this->num;}$this->num = match ($this->type) {1 => $this->num + $this->gap,2 => $this->num - $this->gap,};}public function doguessonce() {var_dump("resultnum:" . $this->resultnum . " name:" . $this->name . " num:" . $this->num);$result = false;$this->type = 0;match (true) {$this->num == $this->resultnum => $result = true,$this->num > $this->resultnum => $this->type = 2, //减$this->num < $this->resultnum => $this->type = 1//加};$this->result = $result;if (!$result) {$this->getnextnum();}}
}
$persion_list = [new GuessNum("test1", 1),new GuessNum("npc", 2),
];$fibers = [];foreach ($persion_list as $entity) {$fibers[] = new Fiber(function () use ($entity) {while (true) {$entity->doguessonce($entity);Fiber::suspend($entity);}});
}// Start all fibers
$endresult = false;
foreach ($fibers as $fiber) {$value = $fiber->start();if ($value->result) {$endresult = true;var_dump("game end success name:" . $value->name);break;}
}
if (!$endresult) {for ($i = 0; $i < 5; $i++) {foreach ($fibers as $fiber) {$value = $fiber->resume();if ($value->result) {$endresult = true;var_dump("game end success name:" . $value->name);break;}}sleep(1);var_dump("once end");}
}
var_dump("game end ~");

输出

string(30) "resultnum:12 name:test1 num:22"
string(27) "resultnum:7 name:npc num:17"
string(30) "resultnum:12 name:test1 num:21"
string(27) "resultnum:7 name:npc num:15"
string(8) "once end"
string(30) "resultnum:12 name:test1 num:20"
string(27) "resultnum:7 name:npc num:13"
string(8) "once end"
string(30) "resultnum:12 name:test1 num:19"
string(27) "resultnum:7 name:npc num:11"
string(8) "once end"
string(30) "resultnum:12 name:test1 num:18"
string(26) "resultnum:7 name:npc num:9"
string(8) "once end"
string(30) "resultnum:12 name:test1 num:17"
string(26) "resultnum:7 name:npc num:7"
string(25) "game end success name:npc"
string(8) "once end"
string(10) "game end ~"

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词