sub lock {
if ( $_[0] ) {
return 0
}
else {
$_[0] += $$;
if ( $_[0] == $$ ) {
return $$;
}
else {
$_[0] -= $$;
return 0;
}
}
}
sub unlock { $_[0] = 0 }
And you can use it with something such as
if ( lock( $dbfile->{lock} ) ) {
# I locked the database and now it's mine
}
else {
# somebody got there first...
}
Now... should I put this into a module?
Lock::Mechanism ?
Lock::Variable ?
is += atomic (Score:2)
Re:is += atomic (Score:1)
I haven't verified it, no, but... does it matter?
OK, I just looked under perlop... and I couldn't find anything stating that += is not atomic...
Re:is += atomic (Score:2)
So, it looks good on paper, but will definitely fail in real life. You really need something like flock(), which is atomic (or uses atomic steps at the bottom on which to build).
It can fail (Score:1)
the sub unlock must be $_[0] -= $$
If not, you could have $_[0] as a negative value, if a different thread unlocks a var while the else part of lock() is running (atfer the +=, before the if)
You must of course ensure that += is atomic, as randal pointed out.
What's your problem with IPC::Semaphore or Thread::Semaphore?
life is short
Re:It can fail (Score:1)
My problem with IPC::Semaphore and Thread::Semaphore is that I didn't think of searching for Semaphore, only for Lock O:-)
But anyway, I don't think the complexity of IPC::Semaphore (not that there's many of it) is needed for such a simple case as the one I've got. I only need to lock one variable in a file, to ensure that the same process doesn't run twice (or more) at the same time. (hum... maybe Semaphore::Sim
Re:It can fail (Score:1)
I really can't recommend that code :).
There are so many dependencies to make it work right: does += flushes the dbfile after the update? is it atomic (locks, read old value, sums with $$, writes new value, unlocks)?
I think you are better off with Fcntl lock stuff...
life is short
Re:It can fail (Score:1)
At least in my case, it does.
is it atomic?
it doesn't lock and read old value and sums... it simply sums $$ and checks if the resulting value is indeed $$ or not; if not, then something else changed that variable meanwhile... which means we should decrement the variable with $$ again and leave it as it was... It's not an atomic thing... it tries to do it, and then it checks out whether it succeeded or not... and it really doesn't matter if it didn't, because tha
Re:It can fail (Score:2)
Let there be light! (Score:1)
Thanks for your patience, as I really wasn't getting it
It's going to be a very particular case, the one that fails, but I'm still going to implement a way to prevent it somehow
Thanks