Hey,
Try some reading at this location...
The Practical PostgreSQL Book (LOCK)
http://www.commandprompt.com/ppbook/index.lxp?lxpwrap=r27479%2ehtm
You're in a kind of race condition and you're not managing processes
very well. The row-locks you want are automatically obtained by the
SELECT ... FOR UPDATE
UPDATE...
and INSERT...
I'm also new to PostgreSQL and I'm still exploring the capabilities
and thinking in possibilities. I don't know whether it is for this kind
of use but take a look at LISTEN and NOTIFY keywords. They provide
together a kind of IPC management.
In theory you can LISTEN for 'ok' in the 2nd process and when the
first finishes what it is doing, it NOTIFies an 'ok', so the 2nd process
takes action and starts its works while the first one LISTENs for 'ok'
and so on...
Remember, I'm not a guru, it is just a suggestion...I don't even know
whether it will work or not for you.
William