Hướng dẫn php sem_get

[PHP 4, PHP 5, PHP 7, PHP 8]

sem_getGet a semaphore id

Description

sem_get[
    int $key,
    int $max_acquire = 1,
    int $permissions = 0666,
    bool $auto_release = true
]: SysvSemaphore|false

A second call to sem_get[] for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.

If key is 0, a new private semaphore is created for each call to sem_get[].

Parameters

key max_acquire

The number of processes that can acquire the semaphore simultaneously is set to max_acquire.

permissions

The semaphore permissions. Actually this value is set only if the process finds it is the only process currently attached to the semaphore.

auto_release

Specifies if the semaphore should be automatically released on request shutdown.

Return Values

Returns a positive semaphore identifier on success, or false on error.

Changelog

VersionDescription
8.0.0 On success, this function returns a SysvSemaphore instance now; previously, a resource was returned.
8.0.0 The type of auto_release has been changed from int to bool.

Notes

Warning

When using sem_get[] to access a semaphore created outside PHP, note that the semaphore must have been created as a set of 3 semaphores [for example, by specifying 3 as the nsems parameter when calling the C semget[] function], otherwise PHP will be unable to access the semaphore.

See Also

  • sem_acquire[] - Acquire a semaphore
  • sem_release[] - Release a semaphore
  • ftok[] - Convert a pathname and a project identifier to a System V IPC key

soger

11 years ago

Actually it looks like the semaphore is automatically released not on request shutdown but when the variable you store it's resource ID is freed. That is a very big difference.

kakkau at grr dot la

6 years ago

It is possible to create an "infinite" amount of semaphores when setting $key = 0.

Run sem_get multiple times
php > sem_get[0,0];

and check the output of
$ ipcs -s

------ Semaphore Arrays --------
key        semid      owner      perms      nsems    
0x00000000 1277952    user       666        3        
0x00000000 1310721    user       666        3

As you can see there were multiple semaphores set up with key 0.
For any other integer sem_get works as expected. It returns another resource id pointing to the semaphore previously created and does not create another semaphore.

kakkau at grr dot la

6 years ago

For those that encounter strange behavior in using sem_acquire[] on resources generated by sem_get[]. Have a look at  sem_get[]'s 4th parameter auto_release. It allows multiple acquisitions through reassignments to resource variables.

./multi.acquire.php

Chủ Đề