2525 */
2626class MutexConcurrencyTest extends \PHPUnit_Framework_TestCase
2727{
28-
2928 /**
3029 * @var \PDO The pdo instance.
3130 */
3231 private $ pdo ;
33-
32+
3433 /**
3534 * Gets a PDO instance.
3635 *
@@ -57,9 +56,13 @@ private function getPDO($dsn, $user)
5756 private function fork ($ concurrency , callable $ code )
5857 {
5958 $ manager = new ProcessManager ();
59+ $ manager ->setDebug (true );
60+
6061 for ($ i = 0 ; $ i < $ concurrency ; $ i ++) {
6162 $ manager ->fork ($ code );
6263 }
64+
65+ $ manager ->check ();
6366 }
6467
6568 /**
@@ -99,21 +102,22 @@ public function provideTestHighContention()
99102 {
100103 $ cases = array_map (function (array $ mutexFactory ) {
101104 $ file = tmpfile ();
102- fputs ($ file , pack ("i " , 0 ));
103- fflush ($ file );
105+ fwrite ($ file , pack ("i " , 0 ));
104106
105107 return [
106108 function ($ increment ) use ($ file ) {
107- fseek ($ file , 0 );
109+ rewind ($ file );
110+ flock ($ file , LOCK_EX );
108111 $ data = fread ($ file , 4 );
109112 $ counter = unpack ("i " , $ data )[1 ];
110113
111114 $ counter += $ increment ;
112115
113- fseek ($ file, 0 );
116+ rewind ($ file );
114117 fwrite ($ file , pack ("i " , $ counter ));
115- fflush ($ file );
116-
118+
119+ flock ($ file , LOCK_UN );
120+
117121 return $ counter ;
118122 },
119123 $ mutexFactory [0 ]
@@ -122,15 +126,16 @@ function ($increment) use ($file) {
122126
123127 $ addPDO = function ($ dsn , $ user , $ vendor ) use (&$ cases ) {
124128 $ pdo = $ this ->getPDO ($ dsn , $ user );
125- $ pdo ->beginTransaction ();
126-
129+
127130 $ options = ["mysql " => "engine=InnoDB " ];
128131 $ option = isset ($ options [$ vendor ]) ? $ options [$ vendor ] : "" ;
129132 $ pdo ->exec ("CREATE TABLE IF NOT EXISTS counter(id INT PRIMARY KEY, counter INT) $ option " );
130-
133+
134+ $ pdo ->beginTransaction ();
131135 $ pdo ->exec ("DELETE FROM counter " );
132136 $ pdo ->exec ("INSERT INTO counter VALUES (1, 0) " );
133137 $ pdo ->commit ();
138+
134139 $ this ->pdo = null ;
135140
136141 $ cases [$ vendor ] = [
@@ -259,6 +264,15 @@ function ($uri) {
259264 return new PHPRedisMutex ($ apis , "test " , $ timeout );
260265 }];
261266 }
267+
268+ if (getenv ("MYSQL_DSN " )) {
269+ $ cases ["MySQLMutex " ] = [function ($ timeout = 3 ) {
270+ $ pdo = new \PDO (getenv ("MYSQL_DSN " ), getenv ("MYSQL_USER " ));
271+ $ pdo ->setAttribute (\PDO ::ATTR_ERRMODE , \PDO ::ERRMODE_EXCEPTION );
272+
273+ return new MySQLMutex ($ pdo , "test " , $ timeout );
274+ }];
275+ }
262276
263277 return $ cases ;
264278 }
0 commit comments