开发者

Synchronization in php

after reading this:

PHP Threads and Synchronization

is my assumption correct that even if I have a singelton pattern, there actually is 1 instance of this class per request? What about flock?

I need to limit a certain functionality/code block in my application to be only executed by one request at a time. The reason is a bit strange, I need to call a cmd-line tool that reads a txt file I create in php and then writes the result to several txt files. To prevent false/strange results the whole code block create file - run cmd-line- read result should be synchronized.

How could i do that? I tried it with a dummy file an lock it with flock -> does not work. I also tried a simple boolean field isLocked to stop further execution of a second request. Also does not work. The issue is the first request is processed c开发者_如何转开发orrectly (data inserted into DB) but the second not and both request do not finish, page loads forever.

Ideas? solutions?

EDIT:

$lockFile = fopen("lock", "r");
while (!flock($lockFile, LOCK_EX)) {

    sleep(1000);
}
// do work
flock($lockFile, LOCK_UN);
fclose($lockFile);

Or:

if (myClass::$isLocked) {
  return false;
}
myClass::$isLocked = true
// do work
myClass::$isLocked = false

both versiosn don't work and both requests freeze, eg. next page never loads. I need to kill apache process.


Yes, Apache serves the request and then moves on. This means unless you put something in the session, it will cease to exist at the end of the request.

If you want to lock files in you can use flock (as you've indicated) : http://php.net/manual/en/function.flock.php

And if you want to manage state in the DB, you can use transactions (mysql link) : http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-transactions.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜