Can't have several threads per session

前端 未结 1 2042
难免孤独
难免孤独 2021-01-20 05:19

I am buidling some webapp and have implemented long-polling (and a command queue in my db) so my server can send commands to my cleint asynchronously, etc. The commands are

相关标签:
1条回答
  • 2021-01-20 05:32

    It's a well known issue/fact that PHP locks session files for the duration of their usage in order to prevent race conditions.

    If you take a look at the PHP source code, (ext/session/mod_files.c) you can see that the ps_files_open function locks the session file, and ps_files_close unlocks it.

    If you call session_start() right at the beginning of your long-running script, and do not explicitly close the session file, it will be locked until the script terminates, where PHP will release all file locks during script shutdown.

    While you are not using the session, you should call session_write_close to flush the session data to disk, and release the lock so that your other "threads" can read the data.

    I'm sure you can imagine what would happen if the file was not locked.

    T1: Open Session
    T2: Open Session
    ...
    T2: Write Data
    T1: Write Data
    

    The data written by thread 2 will be completely overwritten by thread 1, and at the same time, any data that thread 1 wanted to write out, was not available to thread 2.

    0 讨论(0)
提交回复
热议问题