使用PHP同步功能 [英] Synchronized functions using PHP

查看:173
本文介绍了使用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
    }
}

要使用sem_ *函数,必须在sysvsem支持下编译PHP

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天全站免登陆