Skip to content

Commit eea009f

Browse files
committed
work on examples [ci skip]
1 parent 50be8fc commit eea009f

5 files changed

+45
-197
lines changed

examples/ClosureFuture.php

+9-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ class Future extends Thread {
1414

1515
private function __construct(Closure $closure, array $args = []) {
1616
$this->closure = $closure;
17-
$this->args = $args;
17+
$this->args = $args;
18+
$this->owner = Thread::getCurrentThreadId();
1819
}
1920

2021
public function run() {
@@ -40,7 +41,14 @@ public static function of(Closure $closure, array $args = []) {
4041
$future->start();
4142
return $future;
4243
}
44+
45+
public function __destruct() {
46+
if (Thread::getCurrentThreadId() == $this->owner) {
47+
$this->join();
48+
}
49+
}
4350

51+
protected $owner;
4452
protected $closure;
4553
protected $args;
4654
protected $result;

examples/Fetch.php

-90
This file was deleted.

examples/NewSynchronization.php

-45
This file was deleted.

examples/Notifications.php

-61
This file was deleted.

examples/Synchronization.php

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
/*
3+
Rules:
4+
1. only ever wait FOR something
5+
2. only ever wait FOR something
6+
3. only ever wait FOR something
7+
8+
Read the code ...
9+
*/
10+
$thread = new class extends Thread {
11+
12+
public function run() {
13+
14+
$this->synchronized(function(){
15+
$this->awake = true;
16+
$this->notify();
17+
});
18+
}
19+
};
20+
21+
$thread->start();
22+
$thread->synchronized(function() use($thread) {
23+
while (!$thread->awake) {
24+
/*
25+
If there was no precondition above and the Thread
26+
managed to send notification before we entered this synchronized block
27+
we would wait forever!
28+
29+
We check the precondition in a loop because a Thread can be awoken
30+
by signals other than the one you are waiting for.
31+
*/
32+
$thread->wait();
33+
}
34+
});
35+
$thread->join();
36+
?>

0 commit comments

Comments
 (0)