PHP Session locks

At work we have a page that loads multiple PHP scripts (in parallel), using XMLHttpRequest.

Later, we noticed that if one PHP script responds very slowly (i.e. when we put sleep(120) inside), all the others are waiting till the first one finishes loading. In other words: the load is serial, not parallel!

What? Why?!
A little research revealed an interesting phenomena: PHP session locks the session file till the session is closed. By default, the lock starts with session_start() call, and ends at the end of the PHP script!

So - loading multiple pages in parallel (of which all open the same session!), would result in first script locking the session and the others waiting for the release.. Then second lock, etc etc.

Behind the scenes:
session_start() opens the session for writing with fopen("x") - exclusive open. This takes care that a script would wait until the lock is released.

A solution:

In many cases the session is needed for read only, thus there's no good reason for keeping the lock for the whole script..
So for reading only, we can call session_start() to get the session vars, and immediately close it for writing, using session_write_close(). And viola, $_SESSION vars stay!

Hurray!

2 thoughts on “PHP Session locks

  1. Arik

    Interesting. Another way to avoid this is by using one connection (AKA one PHP script) to get the information from all the three scripts.

  2. Pingback: Fallen beim Statuscheck lang laufender PHP-Jobs mit Ajax РI | linux-blog РFa. anracon РDr. M̦nchmeyer

Leave a Reply

Your email address will not be published. Required fields are marked *