Powered By GitBook
system-v-ipc-on-php-runtime
Learn how to use System V shared memory in a PHP App Engine flexible environment app.
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.

Prerequisites

    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
    1
    mkdir myapp
    2
    cd myapp
    Copied!
    2.
    Create an app.yaml file:
    1
    runtime: php
    2
    env: flex
    3
    ​
    4
    manual_scaling:
    5
    instances: 1
    Copied!
    3.
    Create an index.php file:
    1
    <?php
    2
    ​
    3
    # Obtain an exclusive lock
    4
    $key = ftok(__FILE__, 'p');
    5
    $semid = sem_get($key);
    6
    sem_acquire($semid);
    7
    ​
    8
    # Attach shared memory
    9
    $id = shm_attach($key);
    10
    ​
    11
    # Count up
    12
    if (shm_has_var($id, 0)) {
    13
    $count = shm_get_var($id, 0) + 1;
    14
    } else {
    15
    $count = 1;
    16
    }
    17
    ​
    18
    # Save the value
    19
    shm_put_var($id, 0, $count);
    20
    ​
    21
    shm_detach($id);
    22
    ​
    23
    # Release the lock
    24
    sem_release($semid);
    25
    echo sprintf("%d visits so far", $count);
    Copied!
    4.
    Deploy the app:
    1
    gcloud app deploy app.yaml
    Copied!
    5.
    Access the app and see the counts. For example, you can use ab:
    1
    ab -n100 -c10 http://your-project-id.appspot-preview.com/
    Copied!
    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

    1.
    Learn more about System V IPC family​
Last modified 7mo ago