The solution is fairly easy.
In you update statement you place something like this :

update table
set valuefield = newvalue
where keyfield = key
and valuefield = oldvalue

after the update you check affected rows.
if affected rows = 0 then it means that somebody else already changed the
valuefield.
Then you have to do a reread and try again.

Most of the time this is incorporated in a loop that gives the possibility
for a number of retries.

then you have something like this

while retry < 20 do
    update table
    if affected rows <> 0 then break
    retry ++
enddo
if retry = 20 then errormessage


----- Original Message -----
From: "Bennett Haselton" <[EMAIL PROTECTED]>
To: <[EMAIL PROTECTED]>
Sent: Tuesday, November 13, 2001 7:52 AM
Subject: how to do increments in parallel


> Say I have two running programs and both of them periodically want to
> increment a value in a database.  How can I do this so that the increments
> will be performed correctly even if the two programs try to do them at the
> same time?
>
> If I have code like this:
>
> $x = read_value_from_database();
> ++$x;
> write_value_to_database($x);
>
> then the problem is that both programs might try and do their reads at the
> same time, then increment their own copies of the number, and then write
> back the same, incremented number.  If the database system queues requests
> properly, then it won't give any error messages, but the final value of
the
> number in the database will be 1 greater than what it was before, instead
> of what it should be, which is 2 greater.
>
> Is there a single command to increment a numeric value in a database?
That
> way, the database program could queue those requests, run them in order,
> and always end up with the stored number having the right value.
>
> -Bennett
>
> [EMAIL PROTECTED]     http://www.peacefire.org
> (425) 649 9024
>
>
> ---------------------------------------------------------------------
> Before posting, please check:
>    http://www.mysql.com/manual.php   (the manual)
>    http://lists.mysql.com/           (the list archive)
>
> To request this thread, e-mail <[EMAIL PROTECTED]>
> To unsubscribe, e-mail <[EMAIL PROTECTED]>
> Trouble unsubscribing? Try: http://lists.mysql.com/php/unsubscribe.php
>
>


---------------------------------------------------------------------
Before posting, please check:
   http://www.mysql.com/manual.php   (the manual)
   http://lists.mysql.com/           (the list archive)

To request this thread, e-mail <[EMAIL PROTECTED]>
To unsubscribe, e-mail <[EMAIL PROTECTED]>
Trouble unsubscribing? Try: http://lists.mysql.com/php/unsubscribe.php

Reply via email to