forked from krakjoe/pthreads
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClosureFuture.php
60 lines (51 loc) · 1.45 KB
/
ClosureFuture.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
/**
* A synchronized Future for a Closure
*
* This example takes a Closure and executes it in parallel, storing the result
* and fetching the result are synchronized operations
*
* This means that a call to getResult() will block the calling context until a result
* is available
**/
class Future extends Thread {
private function __construct(Closure $closure, array $args = []) {
$this->closure = $closure;
$this->args = $args;
}
public function run() {
$this->synchronized(function() {
$this->result =
(array) ($this->closure)(...$this->args);
$this->notify();
});
}
public function getResult() {
return $this->synchronized(function(){
while (!$this->result)
$this->wait();
return $this->result;
});
}
public static function of(Closure $closure, array $args = []) {
$future =
new self($closure, $args);
$future->start();
return $future;
}
protected $owner;
protected $closure;
protected $args;
protected $result;
}
/* some data */
$test = ["Hello", "World"];
/* a closure to execute in background and foreground */
$closure = function($test) {
return $test;
};
/* make call in background thread */
$future = Future::of($closure, [$test]);
/* get result of background and foreground call */
var_dump($future->getResult(), $closure($test));
?>