Backend Development 3 min read

Analysis of Process Mutual Exclusion in PHP and Automatic Semaphore Release

This article explains how a PHP script uses a named semaphore for process mutual exclusion, demonstrates why a second concurrent process can acquire the semaphore after the first finishes, and clarifies that PHP automatically releases held semaphores when a process terminates.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Analysis of Process Mutual Exclusion in PHP and Automatic Semaphore Release

The article presents a PHP code snippet that implements process mutual exclusion using a named semaphore.

<?php ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(-1); $file = "/www/tp/signal.txt"; $key = ftok($file, "x"); $semaphore = sem_get($file,1,0666,false); sem_acquire($semaphore); echo "hello world"; sleep(20);

The question raised is why, when two processes run this code simultaneously, the second process is not blocked after the first one ends, and whether the process releases the semaphore automatically.

According to the PHP manual, sem_acquire() blocks by default until the semaphore is obtained, but the documentation also notes that any semaphore acquired but not explicitly released will be automatically released when the request ends, triggering a warning. Therefore, when a PHP process terminates, its held semaphore is released automatically.

At the operating‑system level, all opened named semaphores are automatically closed when the process terminates or when execve(2) is invoked.

In summary, in the given PHP code, the first process’s semaphore is automatically released upon termination, allowing the second process to acquire the released semaphore without being blocked.

ConcurrencySemaphorePHPprocess synchronization
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.