views:

161

answers:

5

For concurrency and ensuring the integrity of the data, how would you obtain a mutual-exclusion lock for a given object? Would you need to use locking within the database, or a file, or does PHP support something like this?

A: 

Bare in mind PHP is not multithreaded, so it's unlikely you need anything like this... however, may be needed if you use shared memory, or any other external resources. In such case use smaphores:

http://www.php.net/manual/en/function.sem-acquire.php

http://www.php.net/manual/en/function.sem-get.php

http://www.php.net/manual/en/function.sem-release.php

Johnco
+2  A: 

PHP doesn't support multithreading so there's no locking mechanism for objects. If you want to lock a file you could use flock for that. There's no need to lock database as database engines usually can handle multiple connections.

RaYell
I'm not talking about just "multiple connections", but circumstances when you need to make sure that no one else modifies a given piece of data at the same time. For example, if you have an ATM application. If two people withdraw $50 at the same time, but there is only $50 in the account, one of the people should get an error.
SkippyFire
OK I see, since its not multi threaded I guess it shouldn't be a problem...
SkippyFire
A: 

flock for files.

If you are wanting to use lock in the database, then you would need to use the lock features for those databases. Almost all databases use some form of lock mechanism.

nothing for objects

Sorantis
A: 

It has semaphore support

It has flock http://www.php.net/manual/en/function.flock.php

You can do table locking in MySQL.

Paul
A: 

Like others have answered, since PHP is not multithreaded you do not need to lock on objects. However, if you need to lock on the database you might want to look to transactions. There are many tutorials for doing transactions with PHP and MySQL (and probably for other RMDBS as well).

Markus Johnsson