Synchronized functions using PHP

ぃ、小莉子 提交于 2019-11-28 12:05:46

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

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 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

You are looking for a Semaphore

Bear in mind that using a semaphore (or any other blocking mechanism) can have serious peformance issues, as the requests can not be handled while the semaphore is up.

off the top of my head:

  • function checks if a database field called isFunctionRunning is equal 1. if not start executing
  • you update the database field called isFunctionRunning to 1
  • function does magic here
  • you update the database field called isFunctionRunning to 0

but somehow i think what you are trying to do is "wrong" and can be achieved in another way. could help if you said more details

edit: wasn't aware of php semaphores, the answer above will be way faster.

You can use the "flock" (file locking) function with the "LOCK_EX" (exclusive lock) flag to create a custom "synchronized" function that accepts a handler to be synchronized.

You may may found the code here.

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!