Search code examples
phpcmultithreadingpthreadsthread-local-storage

How to encapsulate global variable in PHP extension for each thread?


I develop some PHP extension. This extension has to work with pthreads together. I have faced with a problem because global variables, declared globally (in top of C code), they are touchable from each PHP thread. For example we have simple PHP extension code written in C laguage:

#include <php.h>

int test_var;

PHP_FUNCTION(set_var) {
  test_var = 123;
}

PHP_FUNCTION(print_var) {
  printf("%d", test_var);
}

If we run the following code in first PHP thread:

set_var();

And then run the following PHP code in the second thread:

print_var();

The output of second thread will be 123. This means I have to use global C variables very carefully. Because it may be overwritten and my script crashed. As variant I can define variables inside the functions and pass this variables to another functions from functions where variable was defined. But I can't do it in some situations when several functions have to have access to some variable. Can anybody tell me a good practices for this, please ?


Solution

  • Make the global variable thread-local be doing:

    _Thread_local int test_var; /* for C11 or higher */
    

    For other versions of C this might do:

    thread_local int test_var; 
    

    or this

    __thread int test_var;