2024 年 PHP Conference Japan

Threaded::notify

(PECL pthreads >= 2.0.0)

Threaded::notify同步

說明

public Threaded::notify(): 布林值

傳送通知到參考的物件

參數

此函式沒有參數。

回傳值

成功時回傳 true,失敗時回傳 false

範例

範例 #1 通知與等待

<?php
class My extends Thread {
public function
run() {
/** 讓這個執行緒等待 **/
$this->synchronized(function($thread){
if (!
$thread->done)
$thread->wait();
},
$this);
}
}
$my = new My();
$my->start();
/** 發送通知給等待中的執行緒 **/
$my->synchronized(function($thread){
$thread->done = true;
$thread->notify();
},
$my);
var_dump($my->join());
?>

以上範例將輸出

bool(true)

新增註記

使用者貢獻的註記 1 則註記

-4
cottton at i-stats dot net
10 年前
似乎有些運算子無法運作。
例如,$thread->array[] = 1; 會失敗

一個簡單的測試
<?php
class My extends Thread
{
public
$array = array('default val 1', 'default val 2'),
$msg = 'default',
$stop = false;

public function
run()
{
while(
true)
{
echo
$this->msg . PHP_EOL;
if(
count($this->array) > 0){
foreach(
$this->array as $val){
var_dump($val);
}
$this->array = array();
}
/** cause this thread to wait **/
$this->synchronized(
function(
$thread){
if(
count($this->array) < 1){
$thread->wait();
}
},
$this
);
echo
PHP_EOL;
if(
$this->stop){
break;
}
}
// while
}
}
$my = new My();
$my->start();

sleep(1); // wait a bit

// test 1 - $thread->array[] = 1;
$my->synchronized(
function(
$thread){
$thread->msg = 'test 1';
$thread->array[] = 1;
$thread->notify();
},
$my
);

sleep(1); // wait a bit

// test 2 - array_push($thread->array, 2);
$my->synchronized(
function(
$thread){
$thread->msg = 'test 2';
array_push($thread->array, 2);
$thread->notify();
},
$my
);

sleep(1); // wait a bit

// test 3 - array_push($thread->array, 2);
$my->synchronized(
function(
$thread){
$thread->msg = 'test 3';
$new = array(3);
$thread->array = array_merge($thread->array, $new);
$thread->notify();
},
$my
);

sleep(1); // wait a bit

$my->stop = true;
?>
out
預設
字串(13) "default val 1"
字串(13) "default val 2"

測試 1

測試 2

測試 3
整數(3)

所以在這種情況下,只有 array_merge() 可以運作。
To Top