Home > Backend Development > PHP Tutorial > Detailed introduction to the code used by php shared memory

Detailed introduction to the code used by php shared memory

黄舟
Release: 2023-03-06 12:58:02
Original
1496 people have browsed it

This article will discuss how to use the inter-process communication mechanism - IPC (Inter-Process-Communication) in the PHP4 environment. The software environment discussed in this article is linux+php4.0.4 or higher. First, we assume that you have installed PHP4 and UNIX. In order for php4 to use shared memory and semaphores, the two extension modules shmop and sysvsem must be activated when compiling the php4 program.

Implementation method: Add the following options when setting up PHP (configure).

--enable-shmop --enable-sysvsem
Copy after login

This allows your PHP system to handle related IPC functions.

 What is IPC?

IPC (Inter-process communication) is a Unix standard communication mechanism that provides a method for different processes on the same host to communicate with each other. There are three basic IPC processing mechanisms: shared memory, semaphores and message queues. In this article we mainly discuss the use of shared memory and semaphores. Regarding the message queue, the author will introduce it specifically in the near future.

Using shared memory segments in PHP

Using shared memory between different processing processes is a good way to achieve mutual communication between different processes. If you write a piece of information to shared memory in one process, then all other processes can also see the written data. Very convenient. With the help of shared memory in PHP, you can achieve different results when different processes run the same PHP script. Or implement real-time query on the number of PHP running at the same time, etc.

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

How to create a shared memory segment? The following code can help you create shared memory.

$shm_id = shmop_open($key, $mode, $perm, $size);
Copy after login

Note that each shared memory segment has a unique ID. In PHP, shmop_open will return the ID of the created shared memory segment. Here 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 storage segment as long as they select the same Key ID. It is customary for us to use the hash value of a string (something like a file name) as the key id. $mode specifies how the shared memory segment is used. Since this is a new creation, the value is ‘c’ – which means create. If you are accessing shared memory that has been created, please use 'a', which means access. The $perm parameter defines the access permissions, in octal format. Please see the UNIX file system help for permission definitions. $size defines the size of shared memory. Although it is a bit like fopen (file processing), you should not think of it as the same as file processing. You will see a little bit of this later in the description.

For example:

$shm_id = shmop_open(0xff3, "c", 0644, 100);
Copy after login

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

If you need to access an existing shared memory segment, you must set the third and fourth parameters to 0 when calling shmop_open.

IPC working status query

Under Unix, you can use a command line program ipcs to query the status of all IPC resources in the system. However, some system requirements require superuser to perform. The picture below is a section of ipcs running results.

In the picture above, the system displays 4 shared memory segments. Note that the fourth key value is 0x00000ff3, which was created by the PHP program we just ran. For the usage of ipcs, please refer to the UNIX User Manual.

How to release shared memory

The way to release shared memory is to call the PHP command: shmop_delete($id)

shmop_delete($id);
Copy after login

$id is what you call The return value of shmop_op stored in shmop_open. Another way is to use the UNIX management command:

ipcrm id, the id is the ID you see using ipcs. It is different from the $id in your program. But be careful, if you use ipcrm to directly delete the shared memory segment, it may cause other processes that are unaware of this situation to cause some unpredictable errors (often with unfavorable results) when referencing this shared memory that no longer exists.

How to use (read and write) shared memory

Use the function shown below to write data to shared memory

int shmop_write (int shmid, string data, int offset)
Copy after login

Where shmid uses shmop_open The handle returned. The $Data variable stores the data to be stored. $offset describes the position of writing the first byte from the beginning of shared memory (starting with 0).

The read operation is:

string shmop_read (int shmid, int start, int count)
Copy after login

  同样,指明$shmid,开始偏移量(以0开始)、总读取数量。返回结果串。这样,你就可以把共享内存段当作是一个字节数组。读几个再写几个,想干嘛就干嘛,十分方便。

  多进程问题的考虑

  现在,在单独的一个PHP进程中读写、创建、删除共享内存方面上你应该没有问题了。但是,显然实际运行中不可能只是一个PHP进程在运行中。如果在多个进程的情况下你还是沿用单个进程的处理方法,你一定会碰到问题 ---- 著名的并行和互斥问题。比如说有2个进程同时需要对同一段内存进行读写。当两个进程同时执行写入操作时,你将得到一个错误的数据,因为该段内存将之可能是最后执行的进程的内容,甚至是由2个进程写入的数据轮流随机出现的一段混合的四不象。这显然是不能接受的。为了解决这个问题,我们必须引入互斥机制。互斥机制在很多操作系统的教材上都有专门讲述,这里不多重复。实现互斥机制的最简单办法就是使用信号灯。信号量是另外一种进程间通讯(IPC)的方式,它同其他IPC机构(管道、FIFO、消息队列)不同。它是一个记数器,用于控制多进程对共享数据的存储。同样的是你可以用ipcs和ipcrm实现对信号灯使用状态的查询和对其实现删除操作。在PHP中你可以用下列函数创建一个新的信号量并返回操作该信号量的句柄。如果该key指向的信号量已经存在,sem_get直接返回操作该信号量的句柄。

int sem_get (int key [, int max_acquire [, int perm]])
Copy after login

  $max_acquire 指明同时最多可以用几个进程进入该信号而不必等待该信号被释放(也就是最大同时处理某一资源的进程数目,一般该值均为一)。$perm指明了访问权限。

  一旦你成功的拥有了一个信号量,你对它所能做的只有2种:请求、释放。当你执行释放操作时, 系统将把该信号值减一。如果小于0那就还设为0。而当你执行请求操作时,系统将把该信号值加一,如果该值大于设定的最大值那么系统将挂起你的处理进程直到其他进程释放到小于最大值为止。一般情况下最大值设为1,这样一来当一个进程获得请求时其他后面的进程只能等待它退出互斥区后释放信号量才能进入该互斥区并同时设为独占方式。这样的信号量常称为双态信号量。当然,如果初值是任意一个正数就表明有多少个共享资源单位可供共享应用。

  申请、释放操作的PHP格式如下:

int sem_acquire (int sem_identifier) 申请 
int sem_release (int sem_identifier) 释放 
其中sem_identifier是调用sem_get的返回值(句柄)。  
一个简单的互斥协议例子 
下面是一段很简单的互斥操作规程。 
$semid=sem_get(0xee3,1,0666); 
$shm_id = shmop_open(0xff3, "c", 0644, 100); 
sem_acquire($semid);      //申请 
/* 进入临界区*/ 
这里,对共享内存进行处理 
sem_release($semid);      //释放
Copy after login

  正如你所看到的,互斥的实现很简单:申请进入临界区,对临界区资源进行操作(比如修改共享内存)退出临界区并释放信号。这样一来就可以保证在同一个时间片中不可能有同时2个进程对同一段共享内存进行操作。因为信号量机制保证一个时间片只能由一个进程进入,其他进程必须等待当前处理的进程完成后方能进入。

  临界区一般是指那些不允许同时有多个进程并发处理的代码段。

  要注意的是:在PHP中必须由同一个进程释放它所占用的信号量。在一般系统中允许进程释放别的进程占用的信号。在编写临界区代码一定要小心设计资源的分配,避免A等B,B等A的死锁情况发生。

  运 用

  IPC的运用是十分广泛的。比如,在不同进程间保存一个解释过的复杂的配置文件、或具体设置的用户等,以避免重复处理。我也曾经用共享内存的技术把一大批PHP脚本必须引用的一个很大的文件放入共享内存,并由此显著提升了Web服务的速度、消除了部分瓶颈。关于它的使用还有聊天室,多路广播等等。IPC的威力取决于你的想象力的大小。如果本文对你有一点点启发,那我不胜荣幸。愿意很你讨论这令人入迷的电脑技术。

<?php
//print_r($res_area);
//$res_area = array("username" => "yanjing5462","password" => "132");
$new_area = serialize($res_area);
//申请共享内存空间
$shm_id = @shmop_open(0xff9, "a", 0, 0);
if(empty($shm_id))
{
echo "创建";
$shm_id = shmop_open(0xff9, "c", 0700, 1048576); //10MB
//$value = "我国已成为全球能源建设规模最大的市场";
//写入共享内存空间
echo $shm_id;
shmop_write($shm_id, $new_area, 0);
  }
else
{
echo &#39;不创建&#39;.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) );
?>
Copy after login

 以上就是php共享内存使用的代码详细介绍的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template