php 7.0 apcu plug-in deadlock issue

最近踩到 apcu 的 deadlock 地雷,紀錄一下

apcu 是個蠻好用的plug-ing, 安裝透過 pecl install 就可以,但先前有人發現(https://daniel.town/php/2016/07/13/osx-apc.html)當多個 request 要寫入同一個 cache entry的時候,可能會造成 deadlock。

比較正常的解決方式是自己做 locking 或 mutex 或 semaphore,但是 php 預設安裝沒有這些東西,必須要從 source 自己做 build (可以參考https://stackoverflow.com/questions/34969325/how-to-install-php7-zts-pthreads-on-ubuntu-14-04)。

我遇到的問題是要把一些資料做 caching,讓多個 request 可以共用,減少對資料庫的讀取。但是每隔一段時間就必須將 cache 做更新,把新的資料(如果有的話)從資料庫更新到 cache去,所以就遇到這樣的問題。

解決方式是把原本寫在 php 程式中的檢查 cache expire改成用 crontab 來做。這樣一勞永逸,永遠只會有一個 request 在做資料更新,寫入 cache entry。