How to implement shared memory between PHP processes on a single server _php tips

Source: Internet
Author: User
Tags mutex php script semaphore unique id

To enable the PHP process to read and write shared memory, developers must first support the IPC function, which is specified when PHP compiles the installation:--enable-shmop and--enable-sysvsem two options .

IPC (inter-process communication) is a UNIX standard mechanism that provides a way to make it possible to interact with one another in different processes on the same host. There are 3 basic IPC processing mechanisms: Shared memory, semaphores, and message queues, respectively. In this article, we mainly discuss the use of shared memory and semaphores.

Using shared memory between different processing processes is a good way to achieve mutual progress between different processes. If you write a piece of information to a 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 to implement real-time queries on the number of simultaneous PHP runs, and so on.

Shared memory allows two or more processes to share a given storage area. Because the data does not need to be replicated between the client and the server, this is the fastest IPC. The only trick to using shared memory is the simultaneous access of multiple processes to a given storage area.

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

Copy Code code as follows:
$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 the shared memory segment. Different processes can share the same segment as long as the same key ID is selected. It is customary for us to use a hash value of a string (something like a filename) 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 already established shared memory then please use ' a ', take access to the meaning. The permissions defined by the $perm parameter, 8, about permission definitions see UNIX File system help. $size defines the size of the shared memory. Although a bit like fopen (file processing) You don't want to be treated like a file. You will see this in the following description.

For example:

Copy Code code as follows:
$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 an existing shared memory segment, you must set the 3rd and 4 parameters to 0 in the call Shmop_open.

Under UNIX, you can use a command-line program to IPCS all the IPC resource states in the system. However, some system requirements require superuser to perform. The following figure shows the results of a IPCS operation.

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

How do I free shared memory?

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

Copy Code code as follows:
Shmop_delete ($id);

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

IPCRM ID, ID is the ID you see with IPCS. It's not the same as the $id in your program. Be careful, however, that if you use IPCRM to delete shared memory segments, it is possible that other processes that do not know the situation have some unpredictable errors (often bad results) when referencing this defunct shared memory device.

How do I use (read and write) shared memory?

Write data to shared memory using the functions shown below

Copy Code code as follows:
int shmop_write (int shmid, string data, int offset)

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

The read operation is:

Copy Code code as follows:
String Shmop_read (int shmid, int start, int count)

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

Now you should have no problem reading, writing, creating, and deleting shared memory in a separate PHP process. However, it is clear that the actual operation is not just a PHP process in operation. If you are using a single process in the case of multiple processes, you are bound to encounter problems-well-known parallel and mutex issues. For example, there are 2 processes that need to read and write to the same memory at the same time. When two processes write at the same time, you will get the wrong data, because the memory will probably be the content of the last process, or even the data written by 2 of processes randomly appear a mixed four-image. This is clearly unacceptable. In order to solve this problem, we must introduce mutual exclusion mechanism. The mutual exclusion mechanism is specifically described in the textbooks of many operating systems, and there is little repetition here. The easiest way to implement a mutex is to use a semaphore . Semaphores are another way of interprocess (IPC), which differs from other IPC mechanisms (pipelines, FIFO, message queues). It is a register that controls the storage of shared data by multiple processes. In the same way, you can use IPCS and IPCRM to implement a query of the state of the semaphore and to implement a delete operation. In PHP you can use the following function to create a new semaphore and return a handle to the semaphore. If the key points to a semaphore that already exists, the Sem_get directly returns the handle that is manipulating the semaphore.

Copy Code code as follows:
int Sem_get int key [, int max_acquire [, int perm]]

$max _acquire indicates that a maximum of several processes can be entered at the same time without waiting for the signal to be released (that is, the number of processes that handle a resource at the same time, typically the value is one). The $perm indicates permissions.

Once you successfully have a semaphore, you can do only 2 kinds of it: request, release. When you perform a release operation, the system will reduce the signal value by one. If less than 0, it is also set to 0. And when you perform a request operation, the system will add the signal value one, if the value is greater than the set maximum then the system will suspend your process until the other process is released to less than the maximum value. In general, the maximum is set to 1, so that when a process obtains a request, the other subsequent process can only wait for it to exit the mutex and then release the semaphore before it can enter the mutex and be set as exclusive. Such a semaphore is often referred to as a dual-state signal volume. Of course, if the initial value is any positive number, it indicates how many shared resource units are available for shared applications.

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.