使用 PHP 的同步函数 [英] Synchronized functions using PHP

查看:33
本文介绍了使用 PHP 的同步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使 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-艺术信号量

这篇关于使用 PHP 的同步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆