阻止并发溢出

<?php
class Transaction {
    // 数据库连接对象
    public $link = null;
    function __construct() {
        $this->link = mysqli_connect ( '192.168.1.222', 'wedai', 'wedai', 'test' );
        mysqli_query ( $this->link, "set names 'UTF-8'" );
        mysqli_query ( $this->link, 'START TRANSACTION' );
    }
    
    // 并发测试
    function concurrent() {
        mysqli_query ( $this->link, "set session transaction isolation level read uncommitted" );
        // 设定延迟,单位微秒,1微秒等于百万分之一秒
        usleep ( rand ( 50, 500 ) );
        // 先查询一次
        $que = $this->selt1 ();
        // 库存大于0时允许减1
        if ($que ['storage_num'] > 0) {
            // 增加条件 WHERE storage_num > 0
            $sql = "UPDATE t1 SET storage_num = storage_num - 1 WHERE storage_num > 0";
            mysqli_query ( $this->link, $sql );
            // 再次查询
            $que = $this->selt1 ();
            if ($que ['storage_num'] >= 0) {
                mysqli_query ( $this->link, "COMMIT" );
                echo "减1成功";
            } else {
                mysqli_query ( $this->link, "ROLLBACK" );
                echo "减1失败";
            }
        }
    }
    //查询返回一条id=1的数据
    function selt1() {
        $sql = "SELECT * FROM t1 WHERE id = 1";
        $que = mysqli_query ( $this->link, $sql );
        return mysqli_fetch_array ( $que );
    }
}
header ( 'Content-type: text/html; charset=utf-8' );
$ransaction = new Transaction ();
$ransaction->concurrent ();
?>

 

posted @ 2015-05-25 21:58  风吹屁股凉冰冰  阅读(277)  评论(0编辑  收藏  举报