当前位置:首页 > PHP教程 > php高级应用 > 列表

php并发加锁问题分析与设计代码实例讲解

发布:smiling 来源: PHP粉丝网  添加日期:2022-04-13 15:19:59 浏览: 评论:0 

在工作项目中,会遇到一些php并发访问去修改一个数据问题,如果这个数据不加锁,就会造成数据的错误,下面我将分析一个财务支付锁的问题。希望对大家有所帮助。

1 没有应用锁机制

1.1 财务支付简化版本代码

  1. <!--?php  
  2. /**  
  3.  * pay.php  
  4.  *  
  5.  * 支付没有应用锁 
  6.  *  
  7.  * Copy right (c) 2016  
  8.  *  
  9.  * modification history:  
  10.  * --------------------  
  11.  * 2018/9/10, by CleverCode, Create  
  12.  *  
  13.  */ 
  14. //用户支付 
  15. function pay($userId,$money) 
  16. { 
  17.  if(false == is_int($userId) || false == is_int($money)) 
  18.  { 
  19.  return false; 
  20.  }  
  21.  //取出总额 
  22.  $total = getUserLeftMoney($userId); 
  23.  //花费大于剩余 
  24.  if($money --> $total) 
  25.  { 
  26.  return false;  
  27.  } 
  28.  //余额 
  29.  $left = $total - $money; 
  30.  //更新余额 
  31.  return setUserLeftMoney($userId,$left); 
  32. } 
  33. //取出用户的余额 
  34. function getUserLeftMoney($userId) 
  35. { 
  36.  if(false == is_int($userId)) 
  37.  { 
  38.  return 0; 
  39.  } 
  40.  $sql = "select account form user_account where userid = ${userId}"; 
  41.  //$mysql = new mysql();//mysql数据库 
  42.  return $mysql->query($sql); 
  43. } 
  44. //更新用户余额 
  45. function setUserLeftMoney($userId,$money) 
  46. { 
  47.  if(false == is_int($userId) || false == is_int($money)) 
  48.  { 
  49.  return false; 
  50.  }  
  51.  $sql = "update user_account set account = ${money} where userid = ${userId}"; 
  52.  //$mysql = new mysql();//mysql数据库 
  53.  return $mysql->execute($sql); 
  54. } 
  55. ?> 

1.2 问题分析

如果有两个操作人(p和m),都用用户编号100账户,分别在pc和手机端同时登陆,100账户总余额有1000,p操作人花200,m操作人花300。并发过程如下。

p操作人:

取出用户的余额1000。

支付后剩余 800 = 1000 - 200。

更新后账户余额800。

m操作人:

取出用户余额1000。

支付后剩余700 = 1000 - 300。

支付后账户余额700。

两次支付后,账户的余额居然还有700,应该的情况是花费了500,账户余额500才对。造成这个现象的根本原因,是并发的时候,p和m同时操作取到的余额数据都是1000。

2 加锁设计

锁的操作一般只有两步,一 获取锁(getLock);二是释放锁(releaseLock)。但现实锁的方式有很多种,可以是文件方式实现;sql实现;Memcache实现;根据这种场景我们考虑使用策略模式。

2.1 类图设计如下

php并发加锁问题分析与设计代码实例讲解

2.2 php源码设计如下

LockSystem.php

  1. <!--?php  
  2. /**  
  3.  * LockSystem.php  
  4.  *  
  5.  * php锁机制 
  6.  *  
  7.  * Copy right (c) 2018 
  8.  *  
  9.  * modification history:  
  10.  * --------------------  
  11.  * 2018/9/10, by CleverCode, Create  
  12.  *  
  13.  */ 
  14. class LockSystem 
  15. { 
  16.  const LOCK_TYPE_DB = 'SQLLock'; 
  17.  const LOCK_TYPE_FILE = 'FileLock'; 
  18.  const LOCK_TYPE_MEMCACHE = 'MemcacheLock'; 
  19.  private $_lock = null; 
  20.  private static $_supportLocks = array('FileLock', 'SQLLock', 'MemcacheLock');  
  21.  public function __construct($type, $options = array())  
  22.  { 
  23.  if(false == emptyempty($type)) 
  24.  { 
  25.  $this--->createLock($type, $options); 
  26.  } 
  27.  }  
  28.  public function createLock($type, $options=array()) 
  29.  { 
  30.  if (false == in_array($type, self::$_supportLocks)) 
  31.  { 
  32.  throw new Exception("not support lock of ${type}"); 
  33.  } 
  34.  $this->_lock = new $type($options); 
  35.  }  
  36.  public function getLock($key, $timeout = ILock::EXPIRE) 
  37.  { 
  38.  if (false == $this->_lock instanceof ILock)  
  39.  { 
  40.  throw new Exception('false == $this->_lock instanceof ILock');  
  41.  }  
  42.  $this->_lock->getLock($key, $timeout);  
  43.  } 
  44.  public function releaseLock($key) 
  45.  { 
  46.  if (false == $this->_lock instanceof ILock)  
  47.  { 
  48.  throw new Exception('false == $this->_lock instanceof ILock');  
  49.  }  
  50.  $this->_lock->releaseLock($key);  
  51.  }  
  52. } 
  53. interface ILock 
  54. { 
  55.  const EXPIRE = 5; 
  56.  public function getLock($key, $timeout=self::EXPIRE); 
  57.  public function releaseLock($key); 
  58. } 
  59. class FileLock implements ILock 
  60. { 
  61.  private $_fp; 
  62.  private $_single; 
  63.  public function __construct($options) 
  64.  { 
  65.  if (isset($options['path']) && is_dir($options['path'])) 
  66.  { 
  67.  $this->_lockPath = $options['path'].'/'; 
  68.  } 
  69.  else 
  70.  { 
  71.  $this->_lockPath = '/tmp/'; 
  72.  } 
  73.  $this->_single = isset($options['single'])?$options['single']:false; 
  74.  } 
  75.  public function getLock($key, $timeout=self::EXPIRE) 
  76.  { 
  77.  $startTime = Timer::getTimeStamp(); 
  78.  $file = md5(__FILE__.$key); 
  79.  $this->fp = fopen($this->_lockPath.$file.'.lock', "w+"); 
  80.  if (true || $this->_single) 
  81.  { 
  82.  $op = LOCK_EX + LOCK_NB; 
  83.  } 
  84.  else 
  85.  { 
  86.  $op = LOCK_EX; 
  87.  } 
  88.  if (false == flock($this->fp, $op, $a)) 
  89.  { 
  90.  throw new Exception('failed'); 
  91.  } 
  92.  return true; 
  93.  } 
  94.  public function releaseLock($key) 
  95.  { 
  96.  flock($this->fp, LOCK_UN); 
  97.  fclose($this->fp); 
  98.  } 
  99. } 
  100. class SQLLock implements ILock 
  101. { 
  102.  public function __construct($options) 
  103.  { 
  104.  $this->_db = new mysql();  
  105.  } 
  106.  public function getLock($key, $timeout=self::EXPIRE) 
  107.  {  
  108.  $sql = "SELECT GET_LOCK('".$key."', '".$timeout."')"; 
  109.  $res = $this->_db->query($sql); 
  110.  return $res; 
  111.  } 
  112.  public function releaseLock($key) 
  113.  { 
  114.  $sql = "SELECT RELEASE_LOCK('".$key."')"; 
  115.  return $this->_db->query($sql); 
  116.  } 
  117. } 
  118. class MemcacheLock implements ILock 
  119. { 
  120.  public function __construct($options) 
  121.  { 
  122.  $this->memcache = new Memcache(); 
  123.  } 
  124.  public function getLock($key, $timeout=self::EXPIRE) 
  125.  {  
  126.  $waitime = 20000; 
  127.  $totalWaitime = 0; 
  128.  $time = $timeout*1000000; 
  129.  while ($totalWaitime < $time && false == $this->memcache->add($key, 1, $timeout))  
  130.  { 
  131.  usleep($waitime); 
  132.  $totalWaitime += $waitime; 
  133.  } 
  134.  if ($totalWaitime >= $time) 
  135.  throw new Exception('can not get lock for waiting '.$timeout.'s.'); 
  136.  } 
  137.  public function releaseLock($key) 
  138.  { 
  139.  $this->memcache->delete($key); 
  140.  } 
  141. } 

3 应用锁机制

3.1 支付系统应用锁

  1. <!--?php 
  2. /**  
  3.  * pay.php  
  4.  *  
  5.  * 支付应用锁 
  6.  *  
  7.  * Copy right (c) 2018  
  8.  *  
  9.  * modification history:  
  10.  * --------------------  
  11.  * 2018/9/10, by CleverCode, Create  
  12.  *  
  13.  */ 
  14. //用户支付 
  15. function pay($userId,$money) 
  16. { 
  17.  if(false == is_int($userId) || false == is_int($money)) 
  18.  { 
  19.  return false; 
  20.  }  
  21.  try 
  22.  { 
  23.  //创建锁(推荐使用MemcacheLock) 
  24.  $lockSystem = new LockSystem(LockSystem::LOCK_TYPE_MEMCACHE);  
  25.  //获取锁 
  26.  $lockKey = 'pay'.$userId; 
  27.  $lockSystem--->getLock($lockKey,8); 
  28.  //取出总额 
  29.  $total = getUserLeftMoney($userId); 
  30.  //花费大于剩余 
  31.  if($money > $total) 
  32.  { 
  33.  $ret = false;  
  34.  } 
  35.  else 
  36.  {  
  37.  //余额 
  38.  $left = $total - $money; 
  39.  //更新余额 
  40.  $ret = setUserLeftMoney($userId,$left); 
  41.  } 
  42.  //释放锁 
  43.  $lockSystem->releaseLock($lockKey);  
  44.  } 
  45.  catch (Exception $e) 
  46.  { 
  47.  //释放锁 
  48.  $lockSystem->releaseLock($lockKey);  
  49.  } 
  50. } 
  51. //取出用户的余额 
  52. function getUserLeftMoney($userId) 
  53. { 
  54.  if(false == is_int($userId)) 
  55.  { 
  56.  return 0; 
  57.  } 
  58.  $sql = "select account form user_account where userid = ${userId}"; 
  59.  //$mysql = new mysql();//mysql数据库 
  60.  return $mysql->query($sql); 
  61. } 
  62. //更新用户余额 
  63. function setUserLeftMoney($userId,$money) 
  64. { 
  65.  if(false == is_int($userId) || false == is_int($money)) 
  66.  { 
  67.  return false; 
  68.  }  
  69.  $sql = "update user_account set account = ${money} where userid = ${userId}"; 
  70.  //$mysql = new mysql();//mysql数据库 
  71.  return $mysql->execute($sql); 
  72. } 
  73. ?> 

3.2 锁分析

p操作人:

获取锁:pay100

取出用户的余额1000。

支付后剩余 800 = 1000 - 200。

更新后账户余额800。

释放锁:pay100

m操作人:

1、等待锁:pay100

2、获取锁:pay100

3、获取余额:800

3、支付后剩余500 = 800 - 300。

5、支付后账户余额500。

6、释放锁:pay100

两次支付后,余额500。非常完美了解决了并发造成的临界区资源的访问问题。

Tags: php并发加锁

分享到: