PHP 7.0.6 Released

The Threaded class

(PECL pthreads >= 2.0.0)

Introduction

Threaded objects form the basis of pthreads ability to execute user code in parallel; they expose synchronization methods and various useful interfaces.

Threaded objects, most importantly, provide implicit safety for the programmer; all operations on the object scope are safe.

Class synopsis

Threaded implements Traversable , Countable , ArrayAccess {
/* Methods */
public array chunk ( integer $size , boolean $preserve )
public integer count ( void )
public bool extend ( string $class )
public Threaded from ( Closure $run [, Closure $construct [, array $args ]] )
public array getTerminationInfo ( void )
public boolean isRunning ( void )
public boolean isTerminated ( void )
public boolean isWaiting ( void )
public boolean lock ( void )
public boolean merge ( mixed $from [, bool $overwrite ] )
public boolean notify ( void )
public boolean pop ( void )
public void run ( void )
public mixed shift ( void )
public mixed synchronized ( Closure $block [, mixed $... ] )
public boolean unlock ( void )
public boolean wait ([ integer $timeout ] )
}

Table of Contents

User Contributed Notes

derkontrollfreak+php at gmail dot com
9 months ago
> Threaded objects, most importantly, provide implicit safety for the programmer; all operations on the object scope are safe.

However, this comes with a trade-off: Operations on the instance scope are slower than on plain PHP objects.

Static properties are not affected as they are thread-local.
312036773 at qq dot com
5 months ago
<?php

class Wallet{
    public
$balance;
    public function
__construct($money){
       
$this->balance = $money;
    }
    public function
getBalance(){
        return
$this->balance;
    }
    public function
setBalance($value){
       
$this->balance = $value;
    }
}
class
MyThread extends Thread{
    private
$wallet;
    private
$std;
    public function
__construct($wallet,$std){
       
$this->wallet = $wallet;
       
$this->std = $std;
    }
    public function
run(){
       
$this->synchronized(function($thread){
               
$hack = $this->wallet;
                if(
$hack->getBalance() - 80 >0){
                   
sleep(1);
                   
$hack->setBalance($hack->getBalance() - 80);
                    echo
$this->getThreadId() . "reduce 80 successful<br/>Current num is:" . $hack->getBalance() . "<Br/>";
                   
//Here is Wrong!  The result is bool(false)????!!!!
                   
var_dump($hack == $this->wallet);
                }
                 else
                     echo
$this->getThreadId() . "reduce fail<br/>Current num is:" . $hack->getBalance() . "<br/>";
           
        },
$this->std);
    }
}
$wallet = new Wallet(200);
$std = new stdClass();
for(
$x=0;$x<3;$x++){
   
$pool[] = new MyThread($wallet,$std);
   
$pool[$x]->start();
}
To Top