How to avoid race condition in php code -


i have experience in java/java ee new php. there small requirement want share value of variable(which contains string token) accross different user requests. issue want make read , write of variable thread safe i. @ time 1 user can read/write in variable.

if in java take lock on object using synchonized keyword , can put code block(read/write) in synchronzed block.

here in php have put token in globals array not getting way can made read , write of variable thread safe. avoiding use external library avoid depdency. please guide me how can achived.

you can use pecl pthreads. needs installed.

you can checkout usage from: http://php.net/manual/en/threaded.synchronized.php

or easier solution lock file.

$fp = fopen("/tmp/lock.txt", "r+");  if (flock($fp, lock_ex)) {  // acquire exclusive lock     ftruncate($fp, 0);      // truncate file     fwrite($fp, "write here\n");     fflush($fp);            // flush output before releasing lock     flock($fp, lock_un);    // release lock } else {     echo "couldn't lock!"; }  fclose($fp); 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -