search
HomeBackend DevelopmentPHP TutorialHow to implement shared memory between PHP processes on a single server_PHP Tutorial

If developers want to enable the PHP process to read and write shared memory, they must first support the IPC function, that is, Specify two options when compiling and installing PHP: --enable-shmop and --enable-sysvsem.

IPC (Inter-process communication) is a Unix standard 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.

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.

Copy code The code is as follows:
$shm_id = shmop_open($key, $mode, $perm, $size);

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 choose 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 have already created shared memory, please use 'a', which means access. The permissions defined by the $perm parameter are 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 this later in the description.

For example:

Copy code The code is as follows:
$shm_id = shmop_open(0xff3, "c", 0644, 100);

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

If you need an existing shared memory segment, you must set the 3rd and 4th parameters to 0 when calling shmop_open.

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)

Copy code The code is as follows:
shmop_delete($id);

$id is the return value of shmop_op saved when you call shmop_open. Another way is to use UNIX management commands:

ipcrm id, 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 the 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

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

Where shmid is the handle returned by shmop_open. 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:

Copy code The code is as follows:
string shmop_read (int shmid, int start, int count)

Similarly, specify $shmid, starting offset (starting from 0), and total number of reads. Return the result string. In this way, you can treat the shared memory segment as a byte array. You can read a few and write a few, and you can do whatever you want. It's very convenient.

Now, you should have no problem reading, writing, creating, and deleting shared memory in a single PHP process. However, it is obviously impossible to have only one PHP process running in actual operation. If you still use the processing method of a single process in the case of multiple processes, you will definitely encounter problems-the famous parallelism and mutual exclusion problems. For example, there are two processes that need to read and write the same memory at the same time. When two processes perform a write operation at the same time, you will get an erroneous data, because the memory segment may be the contents of the last executed process, or even a random mixture of data written by the 2 processes taking turns. The four images are different. This is obviously unacceptable. In order to solve this problem, we must introduce a mutual exclusion mechanism. The mutual exclusion mechanism is specifically described in many operating system textbooks, so I won’t repeat it here. The simplest way to implement a mutual exclusion mechanism is to use a semaphore . Semaphore is another inter-process (IPC) method, which is different from other IPC mechanisms (pipeline, FIFO, message queue). It is a counter used to control the storage of shared data by multiple processes. Similarly, you can use ipcs and ipcrm to query the status of semaphores and delete them. In PHP you can use the following functions to create a new semaphore and return a handle to the semaphore. If the semaphore pointed to by the key already exists, sem_get directly returns the handle to operate the semaphore.

Copy code The code is as follows:
int sem_get(int key [, int max_acquire [, int perm]])

$max_acquire indicates how many processes can enter the signal at the same time without waiting for the signal to be released (that is, the maximum number of processes that can process a certain resource at the same time, generally the value is one). $perm specifies permissions.

Once you successfully own a semaphore, there are only two things you can do with it: request and release. When you perform a release operation, the system will decrease the signal value by one. If it is less than 0, set it to 0. When you perform the requested operation, the system will increase the signal value by one. If the value is greater than the set maximum value, the system will suspend your processing process until other processes are released to a value less than the maximum value. Under normal circumstances, the maximum value is set to 1, so that when a process obtains a request, other subsequent processes can only wait for it to exit the mutex area and then release the semaphore before entering the mutex area and setting it to exclusive mode at the same time. Such semaphores are often called binary semaphores. Of course, if the initial value is any positive number, it indicates how many shared resource units are available for shared applications.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/802210.htmlTechArticleIf developers want to enable the PHP process to read and write shared memory, they must first support IPC functions, that is, PHP compilation Specify two options during installation: --enable-shmop and --enable-sysvsem. IPC (In...
Statement
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
win10gpu共享内存关闭方法win10gpu共享内存关闭方法Jan 12, 2024 am 09:45 AM

对电脑有了解的小伙伴肯定都知道gpu有着共享内存,而许多小伙伴都担心共享内存会导致内存数变小影响电脑而想着关闭它,下面就给大家带来了关闭它的方法,一起看看吧。win10gpu共享内存关闭:注:GPU的共享内存是无法关闭的,但是可以将它的数值设置为最小值。1、开机时按DEL进入BIOS,部分主板需要按F2/F9/F12进入,在BIOS界面的最上方有很多Tab,包含“Main、Advanced”等等设定,找到“Chipset”选项。在下面的界面中找到SouthBridge设定选项,点击Enter进入

Golang函数的多进程之间共享内存的应用方法Golang函数的多进程之间共享内存的应用方法May 17, 2023 pm 12:52 PM

Golang作为一门高并发编程语言,其内置的协程机制和多线程操作实现了轻量级的多任务处理。然而,在多进程处理的场景下,不同进程之间的通信和共享内存成为了程序开发的关键问题。本文将介绍在Golang中实现多进程之间共享内存的应用方法。一、Golang中多进程的实现方式在Golang中,可以通过多种方式实现多进程并发处理,其中包括fork、os.Process、

PHP共享内存函数用法及应用PHP共享内存函数用法及应用Jun 16, 2023 pm 12:27 PM

PHP共享内存函数用法及应用共享内存是指多个进程同时存取同一段内存空间的技术。在并发编程中,共享内存可用于进程间通信,从而实现不同进程之间的数据共享。PHP也提供了相关的共享内存函数,这篇文章将介绍PHP共享内存函数的用法,并且探讨一些实际应用场景。共享内存函数的使用PHP提供了shmop这个扩展模块,使得PHP可以对系统共享内存进行操作。该扩展模块提供的函

在C++中使用共享内存和消息队列在C++中使用共享内存和消息队列Aug 22, 2023 pm 04:21 PM

在C++中,共享内存和消息队列是两个常用的进程间通信方式。它们可以帮助我们在不同的进程之间共享数据和信息,从而实现更加高效的程序设计。共享内存是一种特殊的内存区域,可以被多个进程共享。使用共享内存可以避免复制数据的开销,也能够减少数据在进程间传输的延迟。C++中使用共享内存需要包含<sys/shm.h>头文件,并使用shmget、shmat、sh

多进程编程中遇到的Python问题及解决方法多进程编程中遇到的Python问题及解决方法Oct 08, 2023 pm 04:57 PM

多进程编程中遇到的Python问题及解决方法,需要具体代码示例在Python中,多进程编程是一种常用的并发编程方式。它可以有效利用多核处理器的优势,提高程序的运行效率。然而,在进行多进程编程时,我们也会遇到一些问题。本文将介绍几个常见的问题,并给出相应的解决方法和代码示例。问题1:进程间通信在多进程编程中,进程之间通信是一个基本的需求。然而,由于进程有各自独

如何利用Redis和D语言开发共享内存功能如何利用Redis和D语言开发共享内存功能Sep 22, 2023 am 09:57 AM

如何利用Redis和D语言开发共享内存功能概述:随着计算机应用的复杂性和数据处理的需求增加,共享内存成为了一种常用的数据交换方式。Redis是一款高性能的内存数据库,提供了丰富的数据结构和支持。本文将介绍如何利用Redis和D语言开发共享内存功能,并附上具体代码示例。步骤1:安装Redis和D语言编译器首先,需要在计算机上安装Redis和D语言编译器。Red

如何在 Go 中创建一个共享内存的 Goroutine?如何在 Go 中创建一个共享内存的 Goroutine?Jun 02, 2024 am 11:32 AM

可以通过channel实现共享内存的Goroutine:创建一个channel以指定元素类型。启动一个Goroutine向channel写入数据。在主Goroutine中使用range循环从channel读取数据。通过关闭channel表示完成写入。

PHP多线程编程实践:使用共享内存进行多进程通信PHP多线程编程实践:使用共享内存进行多进程通信Jun 29, 2023 pm 12:50 PM

PHP是一种广泛应用于Web开发的脚本语言,一般情况下,它是单线程执行的。但是,在某些特定的场景下,我们可能需要使用多线程编程来提升程序的性能和效率。本文将介绍如何在PHP中进行多线程编程,并使用共享内存来实现多进程之间的通信。首先,我们需要了解什么是多线程编程和共享内存。多线程编程是一种并发编程的方式,它允许程序在同一时间内执行多个线程,从而提高程序的执行

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.