Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 879
Will Avatar asked Dec 29 '22 12:12

Will


1 Answers

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)

like image 98
SpamapS Avatar answered Jan 01 '23 02:01

SpamapS