Edit on GitHub
Report issue
Page history

Using System V shared memory on the App Engine flexible environment PHP runtime

Author(s): @tmatsuo ,   Published: 2017-01-23

Takashi Matsuo | Developer Programs Engineer | Google

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.


  1. Create a project in the Cloud Console.
  2. Enable billing for your project.
  3. Install the Cloud SDK.

Simple counter with the shared memory

  1. Create a directory

    mkdir myapp
    cd myapp
  2. Create an app.yaml file:

    runtime: php
    env: flex
        instances: 1
  3. Create an index.php file:

    # Obtain an exclusive lock
    $key = ftok(__FILE__, 'p');
    $semid = sem_get($key);
    # 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);
    # Release the lock
    echo sprintf("%d visits so far", $count);
  4. Deploy the app:

    gcloud app deploy app.yaml
  5. 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.


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

  1. Learn more about System V IPC family

Submit a tutorial

Share step-by-step guides

Submit a tutorial

Request a tutorial

Ask for community help

Submit a request

View tutorials

Search Google Cloud tutorials

View tutorials

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.