forked from krakjoe/pthreads
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMySQLi.php
95 lines (77 loc) · 2.22 KB
/
MySQLi.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
/**
* This example illustrates best practice with regard to using MySQLi in multiple threads
*
* For convenience and simplicity it uses a Pool.
**/
class Connect extends Worker {
public function __construct($hostname, $username, $password, $database, $port = 3306) {
$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->port = $port;
}
public function getConnection() {
if (!self::$link) {
self::$link = new mysqli(
$this->hostname,
$this->username,
$this->password,
$this->database,
$this->port);
}
/* do some exception/error stuff here maybe */
return self::$link;
}
protected $hostname;
protected $username;
protected $password;
protected $database;
protected $port;
/**
* Note that the link is stored statically, which for pthreads, means thread local
**/
protected static $link;
}
class Query extends Threaded {
public function __construct($sql) {
$this->sql = $sql;
}
public function run() {
$mysqli = $this->worker->getConnection();
$result = $mysqli->query($this->sql);
if ($result) {
while (($row = $result->fetch_assoc())) {
$rows[] = $row;
}
}
$this->result = $rows;
}
public function getResult() {
return $this->result;
}
protected $sql;
protected $result;
}
$pool = new Pool(4, "Connect", ["localhost", "root", "", "mysql"]);
$pool->submit
(new Query("SHOW PROCESSLIST;"));
$pool->submit
(new Query("SHOW PROCESSLIST;"));
$pool->submit
(new Query("SHOW PROCESSLIST;"));
$pool->submit
(new Query("SHOW PROCESSLIST;"));
$pool->submit
(new Query("SHOW PROCESSLIST;"));
$pool->submit
(new Query("SHOW PROCESSLIST;"));
$pool->shutdown();
/* ::collect is used here for shorthand to dump query results */
$pool->collect(function($query){
var_dump(
$done = $query->getResult());
return count($done);
});
?>