温馨提示×

php中线程如何实现条件变量

PHP
小樊
93
2024-08-13 23:12:41
栏目: 编程语言

在PHP中,线程的条件变量可以通过使用Threaded类的wait()notify()方法来实现。下面是一个简单的示例:

<?php class MyThread extends Thread { private $mutex; private $cond; public function __construct(Threaded $mutex, Threaded $cond) { $this->mutex = $mutex; $this->cond = $cond; } public function run() { $this->mutex->synchronized(function($mutex) { $this->cond->wait($mutex); echo "Thread is notified.\n"; }, $this->mutex); } public function notify() { $this->mutex->synchronized(function($mutex) { $this->cond->notify(); }, $this->mutex); } } $mutex = new Threaded(); $cond = new Threaded(); $thread = new MyThread($mutex, $cond); $thread->start(); // 主线程等待1秒后通知子线程 sleep(1); $thread->notify(); $thread->join(); ?> 

在这个示例中,我们创建了一个MyThread类,它接受一个Threaded类型的互斥锁mutex和条件变量cond作为参数。在run()方法中,子线程首先对互斥锁进行加锁,然后调用条件变量的wait()方法等待通知。在主线程中,我们等待1秒后调用notify()方法通知子线程。子线程收到通知后输出一条消息。

0