Home php教程 PHP源码 PHP session并发及session读写锁分析

PHP session并发及session读写锁分析

Jun 08, 2016 pm 05:20 PM
function gt lt quot session

关于PHP session并发及session读写锁问题估计各大程序员都不会想到这个问题,因为一般情况我们不会使用session来做并发操作了,但有时也有可能用到,下面整理一个session并发及session读写锁文章供各位参考。

<script>ec(2);</script>

PHP这门程序设计语言简单得令人发指,那是因为PHP的作者们太神通。今天我来谈谈所有的phper都熟悉的session(会话)。

需要说明的是:

1.示例代码中分别以files,redis储存会话数据
2./session/setUserFile和/session/setUserRedis设置user_name,user_id两个key,并sleep了3s
3./session/setLoginFile和/session/setLoginRedis设置last_time一个key

4./session/indexFile和/session/indexRedis模板中两个ajax请求,/session/setUserFile和/session/setUserRedis立即执行,/session/setLoginFile和/session/setLoginRedis延迟300ms,是为了模拟同一个用户,同时在两个页面(请求)修改会话数据

执行结果表象:

请求:/session/indexfile

第一次访问:

PHP session并发及session读写锁分析

第二次访问:

PHP session并发及session读写锁分析

请求:/session/getsessionfile
array(3) { ["user_name"]=> string(10) "xudianyang" ["user_id"]=> string(3) "123" ["last_time"]=> int(1419411695) }
以文件保存会话数据结论:/session/setUserFile执行时间为3.1s,/session/setLoginFile执行时间为2.81s(如果加上ajax延迟刚好两个请求的响应时间都是3.1s)

请求:/session/indexredis

第一次访问:

PHP session并发及session读写锁分析

第二次访问:

PHP session并发及session读写锁分析
请求:/session/getsessionredis
array(2) { ["user_name"]=> string(10) "xudianyang" ["user_id"]=> string(3) "123" }
为什么?

手册中有这样的描述:

void session_write_close ( void )

End the current session and store session data.

Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.

也就是说session是有锁的,为防止并发的写会话数据。php自带的的文件保存会话数据是加了一个互斥锁(session_start()的时候),从而解释了上面呈现的两个请求响应时间相同。但是以redis保存会话数据时,第二个ajax虽然没有阻塞,但是会话数据并没有写入到redis,那我们追溯一下源码就有答案了。

php-5.4.14源码
默认的files的save_handler
php-5.4.14/ext/session/mod_files.c
PHP session并发及session读写锁分析
redis的save_handler
phpredis中的redis_session.c中并无实现session读写锁的机制,那上述如何解释呢?其实如果我们将session的源码大致浏览一下,就可以解释了。因为会话在session_start之后,将会话数据就会读取到$_SESSION(在扩展内部全局变量PS(http_session_vars))中,在PHP_RSHUTDOWN_FUNCTION(session)(请求释放)时,通过php_session_flush(TSRMLS_C)将会话数据写入储存介质,也就是说会话的数据并不是实时写入到储存介质的。
这就解释了,为什么redis保存会话数据时,/session/setLoginRedis看似未将last_time写入到redis,实质是写了,但是当/session/setUserRedis请求释放时(由于最开始会话数据中并无last_time这个key),要将所有的会话数据写入到储存介质,从而覆盖了/session/setLoginRedis请求写的值,到此解释了上述的问题。
测试代码:
Session.php
Copy after login
 代码如下 复制代码
<?php final class SessionController extends YafController_Abstract
{
    public function setUserFileAction()
    {
        session_start();
        $_SESSION['user_name'] = 'xudianyang';
        $_SESSION['user_id']   = '123';

        sleep(3);
        echo json_encode($_SESSION);
        return false;
    }

    public function setLoginFileAction()
    {
        session_start();
        $_SESSION['last_time'] = time();

        echo json_encode($_SESSION);
        return false;
    }

    public function indexFileAction()
    {
        // Auto Rend View
    }

    public function getSessionFileAction()
    {
        session_start();
        var_dump($_SESSION);

        return false;
    }

    public function setUserRedisAction()
    {
        $session = CoreFactory::session();
        $session->set('user_name', 'xudianyang');
        $session->set('user_id', '123');

        sleep(3);
        echo json_encode($_SESSION);
        return false;
    }

    public function setLoginRedisAction()
    {
        $session = CoreFactory::session();
        $session->set('last_time', time());

        echo json_encode($_SESSION);
        return false;
    }

    public function indexRedisAction()
    {
        // Auto Rend View
    }

    public function getSessionRedisAction()
    {
        $session = CoreFactory::session();
        var_dump($_SESSION);

        return false;
    }
}
Copy after login
indexfile.phtml


  <title>测试session并发锁问题</title>
  <meta charset="utf-8">
  <script type="text/javascript" src="/assets/js/jquery-1.10.2.min.js"></script>
  <script type="text/javascript">
      $.ajax({
          url: "/session/setUserFile",
          type: "get",
          dataType: "json",
          success: function(response){
              console.info(response.last_time);
          }
      });
      setTimeout(function(){
          $.ajax({
              url: "/session/setLoginFile",
              type: "get",
              dataType: "json",
              success: function(response){
                  console.info(response.last_time);
              }
          });
      }, 300);
  </script>


同时发起2两个ajax请求

Copy after login
indexredis.phtml


  <title>测试session并发锁问题</title>
  <meta charset="utf-8">
  <script type="text/javascript" src="/assets/js/jquery-1.10.2.min.js"></script>
  <script type="text/javascript">
      $.ajax({
          url: "/session/setUserRedis",
          type: "get",
          dataType: "json",
          success: function(response){
              console.info(response.last_time);
          }
      });
      setTimeout(function(){
          $.ajax({
              url: "/session/setLoginRedis",
              type: "get",
              dataType: "json",
              success: function(response){
                  console.info(response.last_time);
              }
          });
      }, 300);
  </script>


同时发起2两个ajax请求

Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

What should I do if the php session disappears after refreshing? What should I do if the php session disappears after refreshing? Jan 18, 2023 pm 01:39 PM

Solution to the problem that the php session disappears after refreshing: 1. Open the session through "session_start();"; 2. Write all public configurations in a php file; 3. The variable name cannot be the same as the array subscript; 4. In Just check the storage path of the session data in phpinfo and check whether the sessio in the file directory is saved successfully.

How to set session timeout in SpringBoot Session How to set session timeout in SpringBoot Session May 15, 2023 pm 02:37 PM

The problem was found in the springboot project production session-out timeout. The problem is described below: In the test environment, the session-out was configured by changing the application.yaml. After setting different times to verify that the session-out configuration took effect, the expiration time was directly set to 8 hours for release. Arrived in production environment. However, I received feedback from customers at noon that the project expiration time was set to be short. If no operation is performed for half an hour, the session will expire and require repeated logins. Solve the problem of handling the development environment: the springboot project has built-in Tomcat, so the session-out configured in application.yaml in the project is effective. Production environment: Production environment release is

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

How to solve the problem that the Springboot2 session timeout setting is invalid How to solve the problem that the Springboot2 session timeout setting is invalid May 22, 2023 pm 01:49 PM

Problem: Today, we encountered a setting timeout problem in our project, and changes to SpringBoot2’s application.properties never took effect. Solution: The server.* properties are used to control the embedded container used by SpringBoot. SpringBoot will create an instance of the servlet container using one of the ServletWebServerFactory instances. These classes use server.* properties to configure the controlled servlet container (tomcat, jetty, etc.). When the application is deployed as a war file to a Tomcat instance, the server.* properties do not apply. They do not apply,

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

What is the default expiration time of session php? What is the default expiration time of session php? Nov 01, 2022 am 09:14 AM

The default expiration time of session PHP is 1440 seconds, which is 24 minutes, which means that if the client does not refresh for more than 24 minutes, the current session will expire; if the user closes the browser, the session will end and the Session will no longer exist.

See all articles