Accessing the $_SESSION variable from pthreads

2019-03-01 11:36发布

I'm having an issue accessing the session variable from functions called from Thread objects using the pthreads library for PHP.

When the function is called from the main thread, no errors occur and everything runs fine.

When run from a Thread object however, I get the following errors:

> PHP Notice:  Undefined variable: _SESSION
> PHP Notice:  Undefined index: Properties Manager
> PHP Fatal error:  Call to a member function getGroupValue() on a non-object

The line numbers specified by the errors all point to this code block:

function connect_mysql_db($database, $write = false) {
    $properties = $_SESSION['Properties Manager'];

    if(!isset($database) || strlen($database)==0){
        throw new Exception("No database specified");
    }

    // Read appropriate host, port, dbname, user & pass for this database
    $host    = $properties->getGroupValue($database, DB_HOST);
    $port    = $properties->getGroupValue($database, DB_PORT);
    $db_name = $properties->getGroupValue($database, DB_NAME);
    ...Removed unnecessary code...
}

A little searching says that I should be able to remedy this issue by putting session_start(); at the top of my file. After doing this, the other errors are still printed in addition to:

> PHP Notice:  A session had already been started - ignoring session_start()

So my main question: Is there something special that I need to do when using pthreads in order to access the super-global session? Or is there something completely different at play here that I am missing?

Edit: Yes, I have tried global $_SESSION; as well.

1条回答
SAY GOODBYE
2楼-- · 2019-03-01 11:52

After a bit more research, it seems that the session variable is not thread safe and in fact locks entirely until the session is closed. I had to remove references to the session and simply pass the needed information to the function or reinitialize it.

Luckily there isn't a performance downfall of the property manager being created.

查看更多
登录 后发表回答