Code details for PHP shared memory usage

Source: Internet
Author: User
Tags unique id
This article will discuss how to use the interprocess communication mechanism--IPC (inter-process-communication) in the PHP4 environment. The software environment discussed in this article is linux+php4.0.4 or later. First, let's assume that you've installed PHP4 and UNIX, and in order for the PHP4 to use shared memory and semaphores, you must activate both the SHMOP and Sysvsem extensions when compiling the PHP4 program.

Implementation method: Add the following options when PHP is set (configure).


This allows your PHP system to handle the relevant IPC functions.

What is IPC?

The IPC (inter-process communication) is a UNIX standard communication mechanism that provides a way to communicate with each other between different processes in the same host. There are 3 basic IPC processing mechanisms: They are shared memory, semaphores, and message queues, respectively. In this article we mainly discuss the use of shared memory and semaphore. About Message Queuing, the author will be specially introduced in the near future.

Using shared memory segments in PHP

Using shared memory between different processing processes is a good way to achieve communication between different processes. If you write a piece of information to the shared memory in a process, all other processes can also see the data being written. Very convenient. With the help of shared memory in PHP, you can implement different processes to return different results when running the same PHP script. or implement a real-time query on the number of concurrent PHP runs, and so on.

Shared memory allows two or more processes to share a given storage area. This is the fastest IPC because the data does not need to be replicated between the client and the server. The only trick to using shared memory is that multiple processes synchronize access to a given storage area.

How do I create a shared memory segment? The following code can help you build shared memory.

$shm _id = Shmop_open ($key, $mode, $perm, $size);

Note that each shared memory segment has a unique ID, and in PHP, Shmop_open returns the ID of the established shared memory segment, where we use $shm_id to record it. And $key is a key value that we logically represent shared memory segments. Different processes can share the same segment of a bucket simply by selecting the same key ID. We used the hash value of a string (something like the file name) as the key ID. $mode indicates how shared memory segments are used. This is because it is new, so the value is ' C ' – take the meaning of create. If you are accessing shared memory that has already been established, then use the ' a ',--access. $perm parameters define access permissions, 8 binary, see UNIX File system Help for permission definitions. $size defines the size of the shared memory. Although a bit like fopen (file processing) you should not treat it as if it were a file. You will see a little bit of the following description.

For example:

$shm _id = Shmop_open (0XFF3, "C", 0644, 100);

Here we open a shared memory segment key value 0xff3–rw-r-r-format with a size of 100 bytes.

If you need to access an existing shared memory segment, you must set the 3rd, 4 parameters to 0 in the call Shmop_open.

Query for IPC working status

Under UNIX, you can use a command-line program to IPCS the status of all IPC resources in the system. However, some systems require super users to perform. Is the result of a IPCS operation.

The system shows 4 shared memory segments, noting that the 4th key value for 0X00000FF3 is created by the PHP program we just ran. Refer to the UNIX user manual for IPCS usage.

How to free up shared memory?

The way to free shared memory is to invoke the PHP Directive: Shmop_delete ($ID)

Shmop_delete ($id);

$id is the return value of the shmop_op that you call Shmop_open. Another option is to use UNIX's management directives:

IPCRM ID, ID is the ID you see with IPCS. Not the same as the $id in your program. But be careful if you use IPCRM to directly delete shared memory segments then it is possible to cause other processes that do not know this to have some unpredictable errors (often bad results) when referencing the shared memory that is no longer present.

How to use (Read and write) shared memory?

Write data to shared memory using the function shown below

int shmop_write (int shmid, string data, int offset)

Where Shmid is the handle returned with Shmop_open. The $Data variable holds the data to be stored. $offset describes where to write the first byte from the beginning of shared memory (starting at 0).

The read operation is:

String Shmop_read (int shmid, int start, int count)

Also, indicate $shmid, start offset (starting at 0), total read quantity. Returns the result string. This way, you can think of the shared memory segment as a byte array. Read a few and write a few, what you want to do, very convenient.

Considerations for multi-process issues

You should now have no problem with reading, creating, and deleting shared memory in a single PHP process. However, it is clear that the actual operation cannot be just a PHP process running. If you still follow the process of a single process in multiple processes, you are bound to encounter problems----famous parallel and mutex issues. For example, there are 2 processes that need to read and write to the same memory. When two processes write at the same time, you will get an incorrect data because the segment memory will probably be the content of the last executed process, or even the data written by 2 processes in turn randomly appearing a mixed four. This is obviously unacceptable. In order to solve this problem, we must introduce mutual exclusion mechanism. Mutual exclusion mechanisms are specifically described in the textbooks of many operating systems, where there is little repetition. The simplest way to implement a mutex is to use a semaphore. Semaphores are another way of interprocess communication (IPC), which differs from other IPC mechanisms (pipelines, FIFO, Message Queuing). It is a register for controlling the storage of shared data by multiple processes. Also, you can use IPCS and IPCRM to implement a query and delete operations on the semaphore's status. In PHP you can create a new semaphore with the following function and return a handle to the semaphore. If the key is pointing to a semaphore that already exists, Sem_get directly returns a handle to the semaphore operation.

int sem_get (int key [, int max_acquire [, int perm]])

$max _acquire indicates that at the same time a maximum of several processes can be used to enter the signal without waiting for the signal to be released (that is, the maximum number of processes that handle a resource at the same time, which is generally a value of one). The $perm indicates access rights.

Once you have a successful semaphore, there are only 2 things you can do about it: request, release. When you perform the release operation, the system will reduce the signal value by one. If it is less than 0 then it is also set to 0. And when you perform the request operation, the system will add one to the signal value, if the value is greater than the set maximum then the system will suspend your processing process until other processes are released to less than the maximum value. In general, the maximum value is set to 1 so that when a process obtains a request, the other process can only wait until it exits the mutex to release the semaphore before it can enter the mutex and is also set to exclusive. Such a semaphore is often called a two-state semaphore. Of course, if the initial value is any positive number, it indicates how many shared resource units are available for sharing the app.

The PHP format for application and release operations is as follows:

int sem_acquire (int sem_identifier) requests an int sem_release (int sem_identifier) release where Sem_identifier is the return value (handle) of the call Sem_get.  An example of a simple mutex protocol is a very simple mutex operation. $semid =sem_get (0xee3,1,0666); $shm _id = Shmop_open (0XFF3, "C", 0644, 100);      Sem_acquire ($semid);      Request/* Enter the critical section * * Here, the shared memory is processed sem_release ($SEMID); Release

As you can see, the implementation of the mutex is simple: apply to the critical section, operate on critical section resources (such as modifying shared memory) and exit the critical section and release the signal. In this way, it is guaranteed that 2 simultaneous processes in the same time slice will not be able to operate on the same piece of shared memory. Because the semaphore mechanism guarantees that a time slice can only be entered by one process, other processes must wait for the currently processed process to complete before they can enter. The

critical section generally refers to sections of code that do not allow concurrent processing by multiple processes at the same time.

Note that the amount of semaphores that must be consumed by the same process in PHP is required to be freed. In a generic system, a process is allowed to release signals that are consumed by other processes. In writing the critical section code must be careful to design the allocation of resources to avoid a b,b such as a deadlock situation occurs. The use of the

IPC by the

is extensive. For example, a complex configuration file that has been interpreted, or a specific set of users, is saved between different processes to avoid duplication of processing. I've also used the technology of shared memory to put a large number of PHP scripts that must be referenced into shared memory, which significantly improves the speed of Web services and eliminates some of the bottlenecks. There are also chat rooms, multi-channel broadcasts and so on for its use. The power of IPC depends on the size of your imagination. If this article is a little bit of inspiration to you, then I am greatly honored. Would like to discuss this fascinating computer technology with you.

<?php//print_r ($res _area);//$res _area = Array ("username" = "yanjing5462", "Password" and "the"); $new _area = Serialize ($res _area);//apply for shared memory space $shm_id = @shmop_open (0XFF9, "a", 0, 0), if (Empty ($shm _id)) {echo "create"; $shm _id = Shmop_ Open (0XFF9, "C", 0700, 1048576); 10mb//$value = "Our country has become the world's largest energy construction market";//write Shared memory space echo $shm _id;shmop_write ($shm _id, $new _area, 0);  } Else{echo ' do not create '. Time (); Shmop_delete ($shm _id); Shmop_close ($shm _id);} $shmid = Shmop_open (0XFF9, "a", 0, 0);  $my _string = shmop_read ($shmid, 0, 1048576);  Print_r (Unserialize ($my _string));? >

The above is the PHP shared memory use of the code details of the content, more relevant content please pay attention to (!

  • Related Article

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