Home > Mobile >  What happens when two PHP scripts are executed at same moment
What happens when two PHP scripts are executed at same moment

Time:06-19

Assuming I’ve the following code

$num = get_file('number.txt'); // number.txt is zero 
// Here User #2 will enter
$num = $num   $_POST['add'];
save_file($num,'number.txt') // saving changes

Simply, User #1 will send through POST an integer value: 7.

While the script is being executed for user 1: After getting the document and before saving it, User #2 send through POST an integer value: 8

It’s one of two:

  • php won’t execute the script for user #2 before it was finished for user #1 thus we will get a value of 15 (7 8) saved in number.txt
  • php will multi handle both requests thus $num will be zero for both users. Thus the final value in number.txt will be the latest change which is done by user #2 i.e it will be “8”.

I don’t know any tools to test such atomic operations, so i might be missing something.

I am confused about would the final value in number.txt be “8” or “15”.

If the value is ”8”, what is a solution if I’m expecting it to be ”15”

CodePudding user response:

Assuming that your web-sever executes the PHP code in separate threads at the same time, what you’re looking at is the parallel processing of the same task with a single shared resource (your file number.txt). The scenario you describe is called a data race condition. In that case you need to take extra care of the data synchronization — in PHP for example using a mutex.

Take a look at this related question.

  •  Tags:  
  • php
  • Related