-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreads.php
More file actions
129 lines (113 loc) · 2.8 KB
/
Threads.php
File metadata and controls
129 lines (113 loc) · 2.8 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<?php
namespace php\multithreading;
/**
* Class Threads
* @package php\multithreading
*/
class Threads {
/**
* @var string
*/
public $phpPath = 'php';
/**
* @var int
*/
private $lastId = 0;
/**
* @var array
*/
private $descriptorSpec = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w']
];
/**
* @var array
*/
private $handles = [];
/**
* @var array
*/
private $streams = [];
/**
* @var array
*/
private $results = [];
/**
* @var array
*/
private $pipes = [];
/**
* @var int
*/
private $timeout = 10;
/**
* @param $filename
* @param array $params
* @return int
*/
public function newThread($filename, $params=[]) {
$filename_or=$filename;
$filename=explode(" ",$filename);
$filename=$filename[0];
if (!file_exists($filename)) {
echo ('FILE_NOT_FOUND');die;
}
$filename=$filename_or;
$params = addcslashes(serialize($params), '"');
$command = $this->phpPath.' -q '.$filename.' --params "'.$params.'"';
++$this->lastId;
$this->handles[$this->lastId] = proc_open($command, $this->descriptorSpec, $pipes);
$this->streams[$this->lastId] = $pipes[1];
$this->pipes[$this->lastId] = $pipes;
return $this->lastId;
}
/**
* @return bool|string
*/
public function iteration() {
if (!count($this->streams)) {
return false;
}
$read = $this->streams;
$write = null;
$except= null;
stream_select($read, $write, $except, $this->timeout);
/*
Here we take only one thread for workability
actually in the array $read them often several
*/
$stream = current($read);
$id = array_search($stream, $this->streams);
$this->results = stream_get_contents($this->pipes[$id][1]);
if (feof($stream)) {
fclose($this->pipes[$id][0]);
fclose($this->pipes[$id][1]);
proc_close($this->handles[$id]);
unset($this->handles[$id]);
unset($this->streams[$id]);
unset($this->pipes[$id]);
}
return $this->results;
}
/*
Static method to get the parameters of the
command-line options
*/
/**
* @return bool|mixed
*/
public static function getParams() {
foreach ($_SERVER['argv'] as $key => $argv) {
if ($argv == '--params' && isset($_SERVER['argv'][$key + 1])) {
return unserialize($_SERVER['argv'][$key + 1]);
}
}
return false;
}
}
/**
* Class ThreadsException
* @package php\multithreading
*/
class ThreadsException extends Exception {
}