K
K
kadzura2019-05-25 14:18:38
PHP
kadzura, 2019-05-25 14:18:38

Prohibition of parallel (simultaneously launched n times) execution of a php script?

Good day everyone. The problem is this:
With the help of something, the user can simultaneously run the same php script n number of times.
The script at one time looks at the number of records in the table, filtering by the current user, writes to the variable “A”, adds a new record to the table and simply adds +1 to the variable “A”. Well, he continues to do his job.
But when the script is run n times at the same time, the result of the variable "A" is the same, hence the number of records, because everyone looked at the same time.
How to avoid it? So that until one of the scripts is executed, the others are waiting, well, or something like that.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nrgian, 2019-05-25
@kadzura

transaction

O
Oleg Frolov, 2019-05-25
@Digiport

Read a variable from a file, and write to the file with a lock:

function autoinc_id($dataset="common",$min=0) {
    $file = __DIR__ . "/autoinc.json";
    $fp = fopen($file, 'c+');
    flock($fp, LOCK_SH);
    $json = json_decode(file_get_contents($file),true);
    if (!isset($json[$dataset])) {
    $json[$dataset]=$min;
  } else {
    if ($json[$dataset]<$min) {$json[$dataset]=$min;} else {$json[$dataset]++;}
  }
  file_put_contents($file,json_encode($json));
    flock($fp, LOCK_UN);
    fclose($fp);
    return $json[$dataset];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question