What is equivalent of the C# lock statement in PHP

2019-05-10 21:12发布

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?

6条回答
来,给爷笑一个
2楼-- · 2019-05-10 21:29

It has semaphore support

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

You can do table locking in MySQL.

查看更多
forever°为你锁心
3楼-- · 2019-05-10 21:30

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.

查看更多
我命由我不由天
4楼-- · 2019-05-10 21:30

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

查看更多
家丑人穷心不美
5楼-- · 2019-05-10 21:45

PHP can run in multi-threaded environments. Also multiple simultaneous processes can be running, even if the web server is not using multiple threads.

In this case, concurrency problems can still happen.

If you want something similar to lock to solve concurrency problems, you can use semaphores: http://www.php.net/manual/en/function.sem-acquire.php

查看更多
干净又极端
6楼-- · 2019-05-10 21:48

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).

查看更多
Emotional °昔
7楼-- · 2019-05-10 21:54

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

查看更多
登录 后发表回答