1

I have concerns on preventing concurrent writes of the same data. (PHP + MySQL)

I have a simple flow:

SELECT a record -> process the data in PHP -> UPDATE the record

My nightmare scenario (see example below) is User1 and User2 both pull the same record out of the database, and both change and write the record back... Leading to one of the users' changes being washed out without being seen.

Is it possible to run PHP in "single threaded" mode, which will queue the actions of the two users?

Thanks !

Edit:

To make things more clear, here is the scenario I want to avoid:

  • User 1 gets data v1 from DB (SELECT)
  • User 2 gets data v1 from DB (SELECT)
  • User 1 generates data v1.1 (PHP)
  • User 2 generates data v1.1' (PHP)
  • User 1 updates data (UPDATE: v1.1 is in DB)
  • User 2 updates data and erases data v1.1 (UPDATE: v1.1' is in DB)

So I want to make sure that before User 2 gets the data, User 1 has updated it. I do not know whether this is the natural order of things and I have nothing to do, or if I need to put some lock in place.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
maleykith
  • 117
  • 1
  • 6
  • see my Intention Locks answer [Here](http://stackoverflow.com/a/38079598). It uses row-level `INNODB` locking. The lock is in place after Line2 until after the `COMMIT` in the Sample Code chunk that is real small. Make that chunk snappy User 2 is blocked during that time period – Drew Sep 10 '16 at 16:02
  • PHP is single threaded, but each request will make PHP to parse and execute the script. – Charlotte Dunois Sep 10 '16 at 16:03
  • @CharlotteDunois the question is about data. No one really cares about what is going on with PHP :p – Drew Sep 10 '16 at 16:05
  • @Drew if PHP modifies your datas in DB, we care about PHP :) – singe batteur Sep 10 '16 at 16:05
  • 1
    @Drew PHP is relevant if PHP modifies and updates data in a DB. – Charlotte Dunois Sep 10 '16 at 16:07
  • it is the db engine that enforces ACID. Unless of course you are all going to implement Semaphores and Mutexes in PHP and try to make Concurrency control out of it. In which case, good luck selling that to a data architect – Drew Sep 10 '16 at 16:08

1 Answers1

0

As far as i know, there is no threading in PHP, but APIs like pthreads http://www.php.net/manual/en/intro.pthreads.php

can be used for threading:

It includes all the tools you need to create multi-threaded applications

by the way this question is discussed a lot on SO ...

singe batteur
  • 401
  • 2
  • 14