使用 PHP 的同步函数

2022-01-22 00:00:00 synchronization php synchronized

如何使 PHP 中的函数同步,从而不会同时执行相同的函数?第二个用户必须等到第一个用户完成该功能.然后第二个用户可以执行该功能.

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 can execute the function.

谢谢

推荐答案

这基本上归结为在某处设置一个标志,该函数被锁定并且在第一个调用者从该函数返回之前无法执行.这可以通过多种方式完成:

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:

  • 使用锁定文件(第一个函数锁定一个文件名f.lok",第二个函数根据该评估检查锁定文件是否存在并执行或不执行)
  • 在数据库中设置标志(不推荐)
  • 按照@JvdBerg 的建议使用信号量(最快)

在编写并发应用程序时,请始终注意竞争条件和死锁!

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

更新使用信号量(未测试):

UPDATE using semaphores (not tested):

<?php

define('SEM_KEY', 1000);

function noconcurrency() {
    $semRes = sem_get(SEM_KEY, 1, 0666, 0); // get the resource for the semaphore

    if(sem_acquire($semRes)) { // try to acquire the semaphore. this function will block until the sem will be available
        // do the work 
        sem_release($semRes); // release the semaphore so other process can use it
    }
}

PHP 需要在编译时支持 sysvsem 才能使用 sem_* 函数

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

这里有一个在 PHP 中使用信号量的更深入的教程:

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

http://www.re-cycledair.com/php-dark-艺术信号量

相关文章