bourneli
bourneli

Reputation: 2230

LAMP: Why php in apache will not race for the mysql db connection?

PHP function mysql_connect returns an existing connection, if not setting the forth parameter '$new_link' TRUE explicitly.
In the apache environment, does calling mysql_connect without setting $new_link TRUE might cause racing condition for the mysql connection resource?
In CLI environment, I have proved that the race condition does appear. But not in apache. So, why? Does apache only use one process model? CLI code example as following:

// create share memory
$nShmKey = ftok(__FILE__, 'i');
$nShmID = shm_attach($nShmKey, strlen($sArr) * 2);

// write the array to the shared memory
$nArrKey = 1;
shm_put_var($nShmID, $nArrKey, $arr);

// create semphore
$nSemID = sem_get(1, 1);

// child process consume the data in the shm
for($i = 0; $i < PROC_NUM; ++$i) {
    $nPID = pcntl_fork();

    if ($nPID == 0) {
        // child
        // create db link
        $oLink = mysql_connect(
                'my_server', 
                'my_user', 
                'my_password', 
                TRUE /*if set this false, it will cause race condition in each child*/
        );
        while (true) {
            sem_acquire($nSemID);

            // get the value
            $arrCur = shm_get_var($nShmID, $nArrKey);

            if (0 == count($arrCur) || $arrCur == FALSE) {
                // value out
                sem_release($nSemID);
                break;
            }
            $nVal = array_pop($arrCur);
            if (FALSE == shm_put_var($nShmID, $nArrKey, $arrCur)) {
                die('Failed to write array to shm');
            }
            sem_release($nSemID);

            // just insert the result to db
            mysql_query("INSERT INTO some_table(val) VALUES({$nVal})", $oLink);
        }
        exit(0);
    }
}

// wait for children
$n = 0;
while ($n < PROC_NUM) {
    $nStatus = -1;
    $nPID = pcntl_wait($nStatus, WNOHANG);
    if ($nPID > 0) {
        echo "{$nPID} exit\n";
        ++$n;
    }
}

// clear shm
sem_remove($nSemID);
shm_remove($nShmID);
echo "finished\n";
?>

I know that mysql link will not works well between multi-process, my question is: Why, in apache, does the race condition for mysql link not happen?

Upvotes: 0

Views: 130

Answers (1)

troelskn
troelskn

Reputation: 117517

No, it will only reuse the same connection within the running process (the same script). And since PHP scripts are generally not multi-threaded, there's not problem. If you fork processes, you should be aware that you are then sharing the same connection, but that's a special case.

There is an option to use persistent connections, which is a kind of connection pool, where connections are shared across processes. But even then, the same connection won't be dished out to two processes at the same time. In general, using persisten connections is not worth it though, since MySql is very fast at connecting.

Upvotes: 2

Related Questions