appserver-io / fhreads

基于fhreads php扩展的PHP用户空间线程库

dev-master 2016-05-26 16:51 UTC

This package is auto-updated.

Last update: 2024-09-18 03:09:39 UTC


README

基于fhreads php扩展的PHP用户空间线程库

这是什么?

基于我们的php ext fhreads,在PHP用户空间中直接实现线程实用程序的实现。

如何使用?

此库处于早期开发阶段。请谨慎使用。

这是一个简单的示例,演示如何使用共享数据对象作为普通的PHP对象,并具有线程安全的计数器属性。

<?php

require_once 'vendor/autoloader.php';

use AppserverIo\Fhreads\Thread;

// define counter thread class which counts the shared data objects counter property
class CounterThread extends Thread
{
    /**
     * Constructor which refs the shared data object to this
     * 
     * @param object $data
     */
    public function __construct($data)
    {
        $this->data = $data;
    }
    
    public function run()
    {
        fhread_mutex_lock($this->data->mutex);
        ++$this->data->counter;
        $this->data->{$this->getThreadId()} = $this->getThreadId();
        fhread_mutex_unlock($this->data->mutex);
    }
}

$data = new \stdClass();
$data->mutex = fhread_mutex_init();
$data->counter = 0;

$ths = array();
$tMax = 10;

// initiate threads
for ($i = 1; $i <= $tMax; $i++) {
    $ths[$i] = new CounterThread($data);
}
// start threads
for ($i = 1; $i <= $tMax; $i++) {
    $ths[$i]->start();
}
// wait for all thread to be finished by joining them
for ($i = 1; $i <= $tMax; $i++) {
    $ths[$i]->join();
}

// echo status
echo "$tMax threads finished..." . PHP_EOL;
// dump shared data object
var_dump($data);
// echo status
echo PHP_EOL . "finished script!" . PHP_EOL;

这将给我们带来惊人的输出! :)

10 threads finished...
object(stdClass)#1 (12) {
  ["mutex"]=>
  int(19463520)
  ["counter"]=>
  int(10)
  ["139792551667456"]=>
  int(139792551667456)
  ["139792533702400"]=>
  int(139792533702400)
  ["139792506754816"]=>
  int(139792506754816)
  ["139792488789760"]=>
  int(139792488789760)
  ["139792515737344"]=>
  int(139792515737344)
  ["139792524719872"]=>
  int(139792524719872)
  ["139792479807232"]=>
  int(139792479807232)
  ["139792560649984"]=>
  int(139792560649984)
  ["139792542684928"]=>
  int(139792542684928)
  ["139792497772288"]=>
  int(139792497772288)
}

finished script!

请参阅examples文件夹以获取更多使用演示。

更多文档和示例即将推出...