there is a block of code (let's call it $ foo-> bar ()) which should be executed once and only once. How to organize it in a multi-user scenario?

I will explain that there is a space.php script that is accessed by a multitude of users, in a particular case 20 people.

we check if all users gave an answer and, if all, execute the code $ foo-> bar () if not, the user is prompted to give an answer or wait for other participants if the answer is given.

in fact, I need to fill $ foo-> bar () only when the last user gives an answer, or after a timeout

at the end of the work $ foo-> bar () we begin a new round, and all users can again give an answer. during the work $ foo-> bar () is logging its execution, from which it can be seen that the code is initialized several times.

I see the problem: users (user1, user2, ...., user20) access the script space.php user1, user2 and user3 answered, wait, wait, wait, refreshing the page each time $ foo-> bar () does not can be executed until the last user user10 has given. user1, user2 and user3 update and wait for user10 finally gives an answer and starts $ foo-> bar () user1 and user3 refreshing the page also launch $ foo-> bar () by cloning the process. since the first process has not yet been completed, the conditions for the launch are met.

OK. make a crutch. in the database, in the table of the script that unites users, added the startrun default 0 field and, after launching $ foo-> bar (), we check the startrun value: if 1, the process is already running. waiting for execution. if 0 - set startrun = 1 to prevent the process from cloning, and start the process $ foo-> bar ()

The problem is that the crutch does not work. Based on the logs, the code still runs several times.

So, how to run the code, one time only, in a multi-user script?

  • Do you run $foo->bar() when the value 1 in the database is independent of anything? Look for the jamb in your code. If the logs show that $foo->bar() several times at the same time, when the value is 0 in the database, then there is a problem with simultaneous access. It is treated by creating a transaction, locking the string. - ArchDemon
  • I corrected a little and added a post - Moral Sufferer
  • This is done through a transaction. Start the transaction. Take from the database the number of answers. If it matches the number of users, run $foo->bar() . Complete the transaction. - ArchDemon
  • transactions? I can not yet say whether this solution will suit me. - Moral Sufferer
  • I was offered to make a socket server or a daemon that would work in the background, excluding the call by the user. Looking for options, there must be something simpler! - Moral Sufferer

0