PHP Semaphore Basic Usage Example detailed _php skill

Source: Internet
Author: User
Tags exception handling mutex php error php programming semaphore

This article illustrates the basic usage of PHP semaphores. Share to everyone for your reference, specific as follows:

Some theoretical basis:

semaphores : Also known as semaphores, semaphore are used to resolve processes (thread synchronization issues), similar to a lock, acquire a lock before access (get no Wait), and release the lock after access.
Critical Resource : A resource that only one process is allowed to access at a time.
Critical Area : The code that accesses critical resources in each process is called a critical section
Process Mutex : two or more processes cannot enter a critical region of the same set of shared variables at the same time, that is, one process is accessing the critical resource and the other process must wait for access.
process Synchronization focuses on how to determine the order of execution between several processes and how to avoid data competition, that is, how to enable multiple processes to work together in a good way

Example: (from Baidu Encyclopedia)

Take the operation of a parking lot as an example. For simplicity's sake, let's say that there are only three parking spaces in the parking lot, and three parking spaces are empty. If five cars come in at the same time, the doorman will allow three of them to enter directly, then put down the car stop, the rest of the car must wait at the entrance, after the car also have to wait at the entrance. At this time, there is a car out of the car park, the doorman learned that after the opening of the car stop, into the outside of a car, if you leave two, you can put two, so reciprocating.

In this parking system, parking is a public resource, each car is like a thread, the gatekeeper is the role of the signal.

$key =ftok (__file__, ' t ');
/**
 * Get a semaphore resource
 int $key [, int $max _acquire = 1 [, int $perm = 0666 [, int $auto _release = 1]]] 
 $max _acquire : How many processes can get the signal at the same time
 $perm: Permission default 0666
 $auto _release: Whether or not to automatically release semaphore
/$sem _id=sem_get ($key);
#获取信号
Sem_acquire ($seg _id);
Do something here is an atomic operation
//release semaphore
sem_release ($seg _id);
Removing the secondary signal from the system
Sem_remove ($sem _id);
Problems that may arise
$fp = Sem_get (Fileinode (__dir__);
Sem_acquire ($FP);
$FP 2 = Sem_get (Fileinode (__dir__), 1));
Sem_acquire ($fp 2);

Implementation of a read-write semaphore in PHP:

Class Rw_semaphore {Const READ_ACCESS = 0;  
  Const WRITE_ACCESS = 1;
  /** * @access Private * @var Resource-mutex semaphore * Private $mutex;
  /** * @access Private * @var resource-read/write semaphore * Private $resource;
  /** * @access Private * @var int * */private $writers = 0;
  /** * @access Private * @var int * */private $readers = 0; /** * Default Constructor * * Initialize the Read/write semaphore/Public Function __construct () {$m
    Utex_key = Ftok ('/home/cyrus/development/php/sysvipc/rw_semaphore.php ', ' m ');    
    $resource _key = Ftok ('/home/cyrus/development/php/sysvipc/rw_semaphore.php ', ' R ');
    $this->mutex = Sem_get ($mutex _key, 1);    
  $this->resource = Sem_get ($resource _key, 1); }/** * destructor * * Remove the Read/write semaphore/Public Function __destruct () {Sem_remove ($
    This->mutex);
  Sem_remove ($this->resource); }/** * Request Acess to the resource * * @param int $mode * @return void */Private Function request_access ($access _type = sel
      f::read_access) {if ($access _type = = self::write_access) {sem_acquire ($this->mutex);
      * Update the writers counter * * * $this->writers++;      
      Sem_release ($this->mutex);
    Sem_acquire ($this->resource);      
      else {sem_acquire ($this->mutex);        
        if ($this->writers > 0 | | | $this->readers = = 0) {sem_release ($this->mutex);        
        Sem_acquire ($this->resource);        
      Sem_acquire ($this->mutex);
      }/* Update the READERS counter * * * $this->readers++;
    Sem_release ($this->mutex); 
      }} Private Function Request_release ($access _type = self::read_access) {if ($access _type = = self::write_access) {
      Sem_acquire ($this->mutex);
      * Update the writers counter * * * $this->writers--; Sem_releasE ($this->mutex);
    Sem_release ($this->resource);
      else {sem_acquire ($this->mutex);
      * Update the READERS counter * * * $this->readers--;
      if ($this->readers = = 0) sem_release ($this->resource);
    Sem_release ($this->mutex); }/** * Request read access to the resource * * @return void/Public Function read_access () {$this ->request_access (self::read_access); /** * Release Read access to the resource * * @return void/Public Function read_release () {$this-&G T;request_release (self::read_access); /** * Request Write access to the resource * * @return void/Public Function write_access () {$this-& Gt;request_access (self::write_access); /** * Release Write access to the resource * * @return void/Public Function write_release () {$this- >request_release (self::write_access);

 }
}

Shared memory + signal to achieve atomic operation

$SHM _key = Ftok ("/home/joeldg/homeymail/shmtest.php", ' R ');
$shmid = Sem_get ($SHM _key, 1024, 0644 | Ipc_creat);
$data = Shm_attach ($shmid, 1024);
We now have our SHM segment
//lets place a variable in there
Shm_put_var ($data, $inmem, "test");
Now lets get it back. We could being in a forked process and still have
//access to this variable.
printf ("Shared contents:%s\n", Shm_get_var ($data, $inmem));
Shm_detach ($data); 

The above source PHP manual sem_get function Comment

For more information about PHP interested readers can view the site topics: "Introduction to PHP Basic Grammar", "PHP error and Exception handling method summary", "PHP Programming algorithm Summary" and "PHP object-oriented Program Design Introduction Course"

I hope this article will help you with the PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.