-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample2.php
75 lines (58 loc) · 1.61 KB
/
example2.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
* Parent and threads exchange values example.
* Thread value doesn't share with other threads, just with parent.
*
*/
require_once("./Thread.php");
require_once("./ThreadException.php");
class TestThread extends Thread
{
public $name;
function __construct($threadName) {
$this->name = $threadName;
parent::__construct();
}
protected function _run()
{
while(1) {
$counter = $this->get('counter');
$counter += 0.01;
$this->set('counter', $counter);
echo "thread [$this->name] increment it's counter to $counter\n";
if ($counter > 5) {
break;
}
sleep(1);
}
return "thread [$this->name] counted to $counter";
}
}
try {
$threadCount = 5;
for($i = 0; $i < $threadCount; $i++) {
$thread[$i] = new TestThread("t-$i");
$thread[$i]->set('counter', 0);
$thread[$i]->run();
}
while(1) {
if (!Thread::hasActive()) {
break;
}
for($i = 0; $i < $threadCount; $i++) {
$counter = $thread[$i]->get('counter');
$counter += 1;
$thread[$i]->set('counter', $counter);
echo "Parent increment thread's [".$thread[$i]->name."] counter to $counter\n";
}
sleep(1);
}
for($i = 0; $i < $threadCount; $i++) {
echo "thread [t-$i] return: '".$thread[$i]->retval()."'\n";
}
// Don't forget to free resources!
Thread::finalize();
}
catch(Exception $e) {
echo $e->getMessage()."\n";
}