PHP shared memory usage instance analysis, php shared instance analysis

Source: Internet
Author: User

PHP shared memory usage instance analysis, php shared instance analysis

This example describes the usage of PHP shared memory. We will share this with you for your reference. The details are as follows:

The shared memory is mainly used for inter-process communication.

There are two sets of extensions for the shared memory in php.

1. enable -- enable-shmop during shmop Compilation

Instance:

$ Shm_key = ftok (_ FILE __, 'T');/** open a shared memory int $ key, string $ flags, int $ mode, int $ size $ flags: a: Access read-only memory segment c: Create a new memory segment, or if the memory segment already exists, open it to read/write w: read/write memory segment n: create a new memory segment. If this memory segment already exists, it will fail $ mode: octal format 0655 $ size: opened data size byte */$ shm_id = shmop_open ($ shm_key, "c", 0644,102 4);/*** the written data must be in string format, and the last offset * Note: The offset must be within the specified range, otherwise, the data cannot be written. **/$ size = shmop_write ($ shm_id, 'songjiankang ', 0); echo "write into {$ size }"; # The read range must also be within the applied memory range, otherwise $ data = shmop_read ($ shm_id, 0,100); var_dump ($ data ); # deleting is only a deletion flag, and does not allow new processes to read data. When no process is read, the system automatically deletes shmop_delete ($ shm_id ); # Close the shmop_close ($ shm_id) of the memory segment );

2. Extend the sem functions with Semaphore (more convenient to use, similar to the key-value format)

// Get the file token key $ key = ftok (_ DIR __, 'A'); // create a shared memory $ shm_id = shm_attach ($ key, 1024,777 ); // resource typeif ($ shm_id = false) {die ('unable to create the shared memory segment ');} # set a value of shm_put_var ($ shm_id, 111, 'value'); # delete a key // shm_remove_var ($ shm_id, 111); # Get A value $ value = shm_get_var ($ shm_id, 111); var_dump ($ value ); # Check whether a key exists // var_dump (shm_has_var ($ shm_id, 111); # Remove shm_remove ($ shm_id) from the system ); # Close the connection shm_detach ($ shm_id) to the shared memory );

Note: These two methods are not common.

A Message Queue implemented with shared memory and semaphores

/***** Using shared memory and semaphores ** supports multi-process and storage of various data types * Note: Use unset () as soon as possible to complete queuing or queuing operations (), to release the critical section **/class ShmQueue {private $ maxQSize = 0; // maximum queue length private $ front = 0; // The queue header pointer private $ rear = 0; // team end pointer private $ blockSize = 256; // block size (byte) private $ memSize = 25600; // maximum shared memory (byte) private $ shmId = 0; private $ filePtr = '. /shmq. ptr '; private $ semId = 0; public function _ construct () {$ shmkey = ftok (_ FILE __, 'T'); $ t His-> shmId = shmop_open( $ shmkey, "c", 0644, $ this-> memSize ); $ this-> maxQSize = $ this-> memSize/$ this-> blockSize; // you can specify a semaphore $ this-> semId = sem_get ($ shmkey, 1 ); sem_acquire ($ this-> semId); // request to enter the critical section $ this-> init ();} private function init () {if (file_exists ($ this-> filePtr )) {$ contents = file_get_contents ($ this-> filePtr); $ data = explode ('|', $ contents); if (isset ($ data [0]) & isset ($ data [1]) {$ This-> front = (int) $ data [0]; $ this-> rear = (int) $ data [1] ;}} public function getLength () {return ($ this-> rear-$ this-> front + $ this-> memSize) % ($ this-> memSize)/$ this-> blockSize ;} public function enQueue ($ value) {if ($ this-> ptrInc ($ this-> rear) ==$ this-> front) {// return false when the team is full ;} $ data = $ this-> encode ($ value); shmop_write ($ this-> shmId, $ data, $ this-> rear ); $ this-> rear = $ this-> PtrInc ($ this-> rear); return true;} public function deQueue () {if ($ this-> front ==$ this-> rear) {// empty team return false;} $ value = shmop_read ($ this-> shmId, $ this-> front, $ this-> blockSize-1 ); $ this-> front = $ this-> ptrInc ($ this-> front); return $ this-> decode ($ value);} private function ptrInc ($ ptr) {return ($ ptr + $ this-> blockSize) % ($ this-> memSize);} private function encode ($ value) {$ data = Serialize ($ value ). "_ eof"; echo ''; echo strlen ($ data); echo''; echo $ this-> blockSize-1; echo ''; if (strlen ($ data)> $ this-> blockSize-1) {throw new Exception (strlen ($ data ). "is overload block size! ");} Return $ data;} private function decode ($ value) {$ data = explode (" _ eof ", $ value ); return unserialize ($ data [0]);} public function _ destruct () {$ data = $ this-> front. '| '. $ this-> rear; file_put_contents ($ this-> filePtr, $ data); sem_release ($ this-> semId); // output critical section, release semaphores}/** // team up $ shmq = new ShmQueue (); $ data = 'test data'; $ shmq-> enQueue ($ data ); * unset ($ shmq); // queue operations $ shmq = new ShmQueue (); $ data = $ shmq-> deQueue (); * unset ($ shmq );*/

In linux, run the ipc command to view and use the ipcrm command to delete the file.

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.