I have good experience in Java/Java EE but I am very new to PHP. There is an small requirement where i want to share value of a variable(which contains a String token) accross different user requests. Now the issue is that i want to make the read and write of this variable thread safe i. at a time only one user can read/write in this variable.
If i was to do it in Java i would just take lock on a object by using synchonized keyword and can put the code block(read/write) in synchronzed block.
Here in PHP i have put the token in GLOBALS array but i am not getting any way by which i can made the read and write of this variable thread safe. I am avoiding to use any external library to avoid depdency. Please guide me how this can be achived.
You can use PECL pthreads. Which needs to be installed.
You can checkout the usage from: http://php.net/manual/en/threaded.synchronized.php
Or the easier solution is to lock a file.
$fp = fopen("/tmp/lock.txt", "r+");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here
");
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
fclose($fp);