Will
Will

Reputation: 24709

Does PHP copy variables when retrieving from shared memory?

If I run an shm_get_var(), will it return a "reference", keeping the data in shared memory?

I'm wanting to keep an array about 50MB in size in shared memory so that it can be used by multiple processes without having to keep multiple copies of this 50MB array hanging around. If shared memory isn't the answer, does anyone have another idea?

Upvotes: 4

Views: 1718

Answers (4)

Akrikos
Akrikos

Reputation: 3662

I'm no expert on this, but would it be possible to write a quick test for this something like the following?

$key = 1234;
//put something small into shared memory
$identifier = shm_attach($key, 1024, 0777);
shm_put_var($identifier, $key, 'shave and a hair cut');

$firstVar = shm_get_var($identifier, $key);
$firstVar .= 'Test String of Doom';
$secondVar = shm_get_var($identifier, $key);

if ($firstVar == $secondVar) {
    echo 'shm_get_var passes by reference';
} else {
    echo 'shm_get_var passes by value';
}

Upvotes: 2

SpamapS
SpamapS

Reputation: 1115

This is the relevant C code snippet from sysvsem.c in PHP 5.2.9 :

/* setup string-variable and serialize */
/* get serialized variable from shared memory */
shm_varpos = php_check_shm_data((shm_list_ptr->ptr), key);

if (shm_varpos < 0) {
    php_error_docref(NULL TSRMLS_CC, E_WARNING, "variable key %ld doesn't exist", key);
    RETURN_FALSE;
}
shm_var = (sysvshm_chunk*) ((char *)shm_list_ptr->ptr + shm_varpos);
shm_data = &shm_var->mem;

PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (php_var_unserialize(&return_value, (const unsigned char **) &shm_data, shm_data + shm_var->length, &var_hash TSRMLS_CC) != 1) {
    PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
    php_error_docref(NULL TSRMLS_CC, E_WARNING, "variable data in shared memory is corrupted");
    RETURN_FALSE;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);

PHP will have to unserialize the entire value every time you call shm_get, which, on a 50MB array, is going to be really really slow.

How about breaking it up into individual values?

Also you might want to consider using APC's variable cache, which will handle all of the shared memory and locking for you (and will also use a hash table for key lookups)

Upvotes: 6

Treby
Treby

Reputation: 1320

you can use shm_remove() Check this out: http://php.net/manual/en/function.shm-remove.php

Upvotes: 1

RageZ
RageZ

Reputation: 27323

form the wording of the documentation

shm_get_var() returns the variable with a given variable_key , in the given shared memory segment. The variable is still present in the shared memory.

I would say yes it's a reference to the shared memory space.

Upvotes: 1

Related Questions