|
Posted by Robert Cummings on 08/28/05 18:31
On Sun, 2005-08-28 at 06:10, Jasper Bryant-Greene wrote:
> Dave Carrera wrote:
> > If multiple users hit the php app at the same time how do i ensure that
> > the correct amount of stock is taken from stock so that a users does not
> > accidentally sell from stock which has already been sold.
>
> Even though multiple users may hit the PHP app "at the same time" (even
> though single processor machines can only actually do one thing at a
> time anyway), they can't all access the tables at the same time.
>
> MySQL does something called table locking, which means that if you're
> updating a table then other clients SELECT statements for the same rows
> will wait until the table has finished being updated (usually not many
> milliseconds...)
>
> This means that if you have something like:
>
> UPDATE stock_table SET stock_count=stock_count-1 WHERE id=935882
>
> and someone else hits it at the same timeand asks:
>
> SELECT stock_count FROM stock_table WHERE id=935882
>
> MySQL won't answer until the UPDATE statement has finished. You likely
> wouldn't even notice the delay though.
>
> In short, don't worry about it unless you're doing more complex things
> where a bunch of statements need to be either all done at once, or not
> done at all. In that case you might like to look in to making your
> tables InnoDB and using the transaction features of MySQL.
Yikes, the above is classic race condition scenario. You select the
stock count, see you have the same amount, then write back an update
statement. In between the select and update another user has just
performed the same select, thinks there's sufficient stock, and then
both users update the database table resulting in a stock of -1 if the
original stock was 1. MySQL doesn't lock the table unless you explicitly
lock it yourself. So the solution to the guys dilemma is to look into
MySQL locking mechanisms. He will want to lock, select, update, unlock.
You are right though that they don't access the table at the same time,
but each is doing multiple actions to the table and those can become
interlaced.
Cheers,
Rob.
--
..------------------------------------------------------------.
| InterJinn Application Framework - http://www.interjinn.com |
:------------------------------------------------------------:
| An application and templating framework for PHP. Boasting |
| a powerful, scalable system for accessing system services |
| such as forms, properties, sessions, and caches. InterJinn |
| also provides an extremely flexible architecture for |
| creating re-usable components quickly and easily. |
`------------------------------------------------------------'
Navigation:
[Reply to this message]
|