What alternative functionality to flock are you looking for?
I do wonder about the use of "unless" together with flock -- this means that, potentially, losing the race has more than one possible consequence (wait for lock or abort) depending on where in the thread a race is lost. Is that intended?
While the OPs code makes little sense, your comment isn't all that clear either. There's no losing the race with flock. The flock is blocking. If someone else gets the lock first, the current process will politely wait till the other is done, and then it gets turn, while no other process using the semaphore will interfere.
Now, I've big questions about any of the OPs code that isn't involved in the locking - but I don't see a problem with the locking in itself.