dragon071111 2011-02-10 22:29
浏览 125
已采纳

实现PHP / MySQL事务锁定机制的正确方法是什么

For example suppose you send a newsletter to several thousand subscribers and you advertise "The first hundred to click on this link get a 10% discount". As an extreme example assume thousands of clicks arrive within a few seconds. What's the correct way of making sure that after exactly the 100th click things are locked so that there is no chance of 101 or 102 customers getting the "congratulations on getting the discount message"

  • 写回答

3条回答 默认 最新

  • dongpo4197 2011-02-10 22:32
    关注

    You could create a lock file and flock($fp, LOCK_EX) it to ensure only one (PHP) process can have it opened at the same time. After locking the file successfully, you process the request and, when finished, flock($fp, LOCK_UN) it.

    $fp is the file handle returned by fopen().

    Of course you can also use mutexes for that, but they are not enabled by default in PHP.

    Here's a flow "chart" for the flock solution:

    1. Open the lock file (can be simply an empty file)
    2. Lock the file. If another process already locked it, this call will block until the other lock is released
    3. Check if the user is still eligible to do whatever he wanted to do
    4. If yes/no, do something
    5. Unlock the file
    6. Close the file
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示