查詢

parallel\Sync::set()函式—用法及示例

「 設定平行計算中共享變數的值 」


函式名:parallel\Sync::set()

適用版本:PHP 7.2.0 及以上版本

用法:parallel\Sync::set() 方法用於設定平行計算中共享變數的值。

語法:

public static void parallel\Sync::set(string $name, mixed $value)

引數:

  • $name:共享變數的名稱,必須是字串型別。
  • $value:要設定的共享變數的值,可以是任意型別的值。

返回值:無返回值。

示例:

<?php
$sharedVariable = new parallel\Sync();

// 在主執行緒中設定共享變數的值
$sharedVariable->set('count', 10);

// 在子執行緒中讀取共享變數的值
$childThread = new parallel\Runtime();
$childThread->run(function() use ($sharedVariable) {
    $count = $sharedVariable->get('count');
    echo "Child thread: count = $count" . PHP_EOL;
});

// 在主執行緒中修改共享變數的值
$sharedVariable->set('count', 20);

// 在主執行緒中讀取共享變數的值
$count = $sharedVariable->get('count');
echo "Main thread: count = $count" . PHP_EOL;
?>

輸出:

Child thread: count = 10
Main thread: count = 20

說明:

  • 在示例中,首先建立了一個 parallel\Sync 物件 $sharedVariable,用於實現共享變數的功能。
  • 在主執行緒中使用 $sharedVariable->set() 方法設定共享變數的初始值為 10。
  • 接著,在子執行緒中使用 $sharedVariable->get() 方法讀取共享變數的值,並輸出結果。
  • 然後,在主執行緒中使用 $sharedVariable->set() 方法修改共享變數的值為 20。
  • 最後,在主執行緒中使用 $sharedVariable->get() 方法讀取共享變數的值,並輸出結果。
補充糾錯
上一個函式: parallel\Sync::wait()函式
下一個函式: parallel\Sync::notify()函式
熱門PHP函式
分享連結