PHP no wait sem_acquire?

Not a specific code question, but a general coding question. I am trying to use a semaphore in a working project to limit the number of users who can access certain processes at the same time.

In my opinion, the following:

$iKey = ftock($sSomeFileLocation,'sOneCharacterString'); //Generate the key if($sem_id = sem_get($iKey)){ //1 user allowed if(sem_acquire($sem_id)){ //Do the limited process here sem_release($sem_id); } } 

The problem that I see here is that if there is already one user who has a semaphore key, the next user just waits until the first user is made, and not just a crash. Does anyone know how, if the max_acquire number was reached, sem_acquire (or the like) would simply return false?

thanks

+4
source share
2 answers

No, this is not possible according to the implementation used by PHP.

According to the semop() man page, it should have the IPC_NOWAIT flag, but it does not look like the PHP implementation does.

In fact, looking at the PHP source code for the sysvsem package , you can clearly see that it will continue to block even if signals interrupt the process lock (line 320). Although this may not be optimal, it is fine if you understand the limitations.

As for your use case, there may be other implementations (for example, blocking files against the file system), which would be very useful for most use cases and be able to do exactly what you need ...

+3
source

Starting with PHP 5.6.1, it supports the $ nowait parameter for sem_acquire:

 bool sem_acquire ( resource $sem_identifier [, bool $nowait = false ] ) 

By the way, the second ftok () parameter in PHP should be a single character string, not a string consisting of several characters, as in your case. for instance

 $project = "c"; $key = ftok(__FILE__, $project); 
0
source

Source: https://habr.com/ru/post/1337870/


All Articles