Synchronized functions using PHP

后端 未结 4 2104
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 02:04

How to make functions in PHP synchronized so that same function won\'t be executed concurrently ? 2nd user must wait till 1st user is done with the function. Then 2nd user

4条回答
  •  無奈伤痛
    2020-12-11 02:58

    This basically comes down to setting a flag somewhere that the function is locked and cannot be executed until the first caller returns from that function. This can be done in a number of ways:

    • use a lock file (first function locks a file name "f.lok", second function checks if the lock file exists and executes or doesn't based on that evaluation)
    • set a flag in the database (not recomended)
    • use semaphores as @JvdBerg suggested (the fastest)

    When coding concurrent application always beware of race conditions and deadlocks!

    UPDATE using semaphores (not tested):

    PHP needs to be compiled with sysvsem support in order to use sem_* functions

    Here's a more in depth tutorial for using semaphores in PHP:

    http://www.re-cycledair.com/php-dark-arts-semaphores

提交回复
热议问题