forked from birdwyx/phpgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselect_producer_consumer.php
69 lines (61 loc) · 1.9 KB
/
select_producer_consumer.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
<?php
use \Go\Chan;
use \Go\Scheduler;
use \Go\Time;
function write_data($ch, $data){
$data_written = new Chan(0);
// try to write data to the channel, if the channel is not available to write, wait a 50ms
// loop until the data is successfully written
select(
[
'case', $ch, "<-", $data, function($value) use($data_written){
echo "data written:";
var_dump($value);
$data_written->close();
}
],
[
'default', function(){
echo "channel full, wait 50ms for consumer to consume\n";
Time::sleep(50*1000*1000);
}
]
)->loop($data_written);
}
function producer($ch, $close){
select(
[
'default', function() use($ch){
$data = rand();
write_data($ch, $data);
}
]
)->loop($close);
}
function consumer($ch, $close){
select(
[
'case', $ch, function($value) {
echo "data consumed:";
var_dump($value);
// wait a 10ms: simulating a slow consumer:
// just to see the output from producer:
// "channel full, wait 50ms for consumer to consume"
Time::sleep(10*1000*1000);
}
]
)->loop($close);
}
// main routine
go( function(){
$ch = new Chan(["capacity"=>20]);
$close = new Chan(0);
go('producer', [$ch, $close]);
go('consumer', [$ch, $close]);
// tell producer and consumer to exit after 10 seconds
// note: Time::sleep follows go convension: time unit in nano-second
// please note the difference with php sleep() witch has time unit in seconds
Time::sleep(10* 1000*1000*1000);
$close->close();
});
Scheduler::join();