Synchronized functions using PHP(使用 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 的同步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 PHP 的同步函数


基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01