"Joshua Beall" <jbeall@donotspam.remove.me.heraldic.us> wrote in message
news:45I0e.20505$b_6.11577@trnddc01...[color=blue]
> Hi All,
>
> I am doing some work where I want to do locking, and prevent scripts from
> running in parallel. I see that I could use the semaphore mechanism, but
> I'd like for my code to be portable, and that extension is not enabled in
> many places.
>
> I need some way for a process to uniquely identify itself. It can then
> look at the storage container (flat file, DB, whatever is appropriate in
> context), check to see if the requested semaphore is available, and if it
> is, acquire it and then mark itself as the owner. It can then check that
> it did in fact get ownership (as opposed to another process which
> attempted to acquire it at the exact same moment) before proceeding.
>
> However I am stumped at the point where it needs to indicate ownership.
> How does the PHP script identify itself? It can't use the script name,
> obviously - lots of instances of the script may be running. It can't use
> session ID - the user might submit duplicate requests, and they would both
> have the same session ID. The best I have been able to think of is to use
> the sha1(microtime()) to generate a unique key. But this isn't quite
> foolproof, as it is theoretically possible, though unlikely, for two
> requests to be at the exact same instant.
>
> The answer that comes to my mind would be to use the process ID. This is
> necessarily unique across the entire server, correct? It seems to be
> exactly what I need. But I can't seem to figure out how to determine the
> current process ID from within PHP. Is this even possible?
>
> Any ideas?
>
> -Josh
>
> p.s. Please forgive me if I have misused the term "semaphore" - I know it
> only from the context I have heard it used in, I don't know the textbook
> definition.
>[/color]
Process ID would not be unique on a multi threaded server and hence not
portable if that is an requirement.
PHP has a function to generate a unique ID if that is what you are after:
http://se.php.net/manual/en/function.uniqid.php
Neither that function guarantees the ID to be unique, if generated on
several hosts at the same microsecond... probably won't happen in a trillion
years though...
You could use a transactional database to generate unique ids or you could
use file locking.
I serialize session requests per session ID by making a lock on the sesssion
ID in MySQL:
"SELECT GET_LOCK('$sessionID', 10)" and "DO RELEASE_LOCK('$sessionID')"
If you wish to serialize requests per script, I would use a lock file and
use file locking. That is how most applications do it.
If you want everything you do to be bullet proof, you will end up spending
most of your time on just that, and not on your application.
Best Regards,
Peter Albertsson