略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Threaded

2024-03-29

Threaded 类

(PECL pthreads >= 2.0.0)

简介

Threaded 对象提供支持 pthreads 操作的基本功能,包括同步方法以及其他对程序员很有帮助的接口。

重要的是,Threaded 提供了隐式的线程安全机制,这个对象中的所有操作都是线程安全的。

类摘要

class Threaded implements Collectable, Traversable, Countable, ArrayAccess {
/* 方法 */
public chunk(int $size, bool $preserve): array
public count(): int
public extend(string $class): bool
public isRunning(): bool
public isTerminated(): bool
publicmerge(mixed $from, bool $overwrite = ?): bool
public notify(): bool
public notifyOne(): bool
public pop(): bool
public run(): void
public shift(): boolean
public synchronized(Closure $block, mixed $... = ?): mixed
public wait(int $timeout = ?): bool
}

目录

add a noteadd a note

User Contributed Notes 3 notes

up
2
jtbibliomania at gmail dot com
2 years ago
It's worth mentioning here that, since v2.0.0, 'Stackable' class was an alias for 'Threaded' class but has been removed since.
up
6
derkontrollfreak+php at gmail dot com
6 years 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.
up
-47
312036773 at qq dot com
6 years 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();
}

官方地址:https://www.php.net/manual/en/class.threaded.php

冷却塔厂家 广告
-- 广告
北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3