Using System V shared memory on the App Engine flexible environment PHP runtime
Contributed by Google employees.
PHP has a wrapper for the System V IPC family of functions including semaphores, shared memory, and inter-process messaging. For more details, visit the official documentation.
Our PHP runtime provides these features out of the box, so you can immediately start using them on App Engine flexible environment. We'll walk through a small demo app to learn how to use them.
Prerequisites
- Create a project in the Cloud Console.
- Enable billing for your project.
- Install the Cloud SDK.
Simple counter with the shared memory
Create a directory
mkdir myapp cd myapp
Create an
app.yaml
file:runtime: php env: flex manual_scaling: instances: 1
Create an
index.php
file:<?php # Obtain an exclusive lock $key = ftok(__FILE__, 'p'); $semid = sem_get($key); sem_acquire($semid); # Attach shared memory $id = shm_attach($key); # Count up if (shm_has_var($id, 0)) { $count = shm_get_var($id, 0) + 1; } else { $count = 1; } # Save the value shm_put_var($id, 0, $count); shm_detach($id); # Release the lock sem_release($semid); echo sprintf("%d visits so far", $count);
Deploy the app:
gcloud app deploy app.yaml
Access the app and see the counts. For example, you can use
ab
:ab -n100 -c10 http://your-project-id.appspot-preview.com/
Access the same URL with a browser to see the counter.
Caveats
This counter application is not for production use at all. The shared memory is not shared among multiple servers, and also the memory will go away when the server restarts. It only demonstrates how they work.
Next step
- Learn more about System V IPC family
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see our Site Policies. Java is a registered trademark of Oracle and/or its affiliates.