PHP和并发 [英] PHP and Concurrency

查看:75
本文介绍了PHP和并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在用PHP进行一些Web开发工作,这使我对这种语言进行了一般的研究.到目前为止,我还不需要使用它与数据库进行交互,但是我知道它提供了许多方便的功能.

I've been doing some web development work in PHP recently which has led me to study up on the language in general. So far I have not needed to use it to interact with a database, but I know it provides a lot of convenient functions for doing so.

尽管我了解基本的SQL并已经对数据库中的数据进行了基本的处理,但是我不理解以PHP/Javascript/SQL为基础的网站开发人员如何能够管理同时修改相同数据的用户时间.

Although I know basic SQL and have worked with basic manipulation of data in a database, I don't understand how web developers who base their websites around PHP/Javascript/SQL are able to manage users modifying the same data at the same time.

例如,假设您有一个二十一点网站,当他们注册时,该网站将用户分为两个团队之一.每次用户赢得比赛时,他们的部分收益将被添加到该团队的累计收益中.

For example, lets say you have a blackjack website which divides users into one of two teams when they sign up. Every time a user wins a game, a portion of their winnings is added to a running total for that team.

因此,可以说执行此功能的函数的伪代码如下所示:

So lets say the pseudo code for the function that does this looks something like this:

... 
$total = mysql_query("SELECT score FROM team1");
$total = $total + $mytotal;
mysql_query("UPDATE team1 SET score='".$total."'");
...

如果两个玩家同时在玩,那么他们很可能会在另一个有机会增加和更新表之前都调用SELECT,因此一个用户的更改将立即被覆盖.

If two players are playing at the same time, it's very possible that they will both call SELECT before the other one has a chance to increment and update the table, so one users changes will be immediately overwritten.

我的问题是,如何避免这种情况?是使用PHP在代码级别完成的,还是您使用的任何数据库提供的功能都可以防止这种情况的发生?

My question is, how does one avoid this? Is it done using PHP at the code level, or are there features provided by whatever database you are using that help to prevent this?

我一直在做一些研究,似乎PHP确实提供了信号量机制,并且我还注意到mysql提供了 LOCK表功能.但是,我不确定在实践中会使用其中的哪一种.

I've been doing some research, and it seems that PHP does provide a semaphore mechanism, and I've also noticed that mysql offers a LOCK table feature. However, I'm not sure which of these, if either, is used in practice.

推荐答案

如果您的实际问题比这个简单示例大,则应将事务与锁表结合使用,以确保用户不会互相覆盖.

IF your real world problem is bigger than this simple example, you should use a transaction in conjunction with lock tables to make sure users don't overwrite each other.

这篇关于PHP和并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆