Examples of exclusive locks in PHP concurrency control

Source: Internet
Author: User

1. Concurrency issues

Concurrency we all know what is the case, here is a concurrent multiple requests to preempt the same resource, directly on the example bar

Request: Index.php?mod=a&action=b&taskid=6

Processing:

$key = "A_b::". $uid. ' _ '. $taskid;
$v = $redis->get ($key);
if ($v = = 1) {
$redis->setex ($key, 10, 1);
Processing logic omitted
}
2. Analysis

Logic seems to be OK, the results found that the database wrote two of the same request results, I read the record time stamp, days! Incredibly the same second.
I use Microtime (true) log the time difference between two requests is actually 0.0001s, that is, $redis->setex ($key, 10, 1); no success yet. The second request has gotten to the same result as the first request. This is not the legendary concurrent preemption resources. This situation heard a lot, in the development process did not deliberately to simulate the experiment.
3. Address

Scenario 1: The first reaction is to add transactions to the processing process (database is MySQL InnoDB), plus the result of the transaction is the first request to succeed the second request will be executed to the back of the check found that the heavy will be rolled back. In fact, MySQL transactions in the guarantee of data consistency is very OK, but by rolling back to ensure that the only resource exclusive cost too much, do the MySQL transaction testing students know that the transaction in the insert is already inserted, rollback after the deletion.
Scenario 2: There is another option is the file exclusive lock in PHP, that is to say that I want to create a new user number * Task number of files to achieve the exclusive resources of each request, if the exclusive resources are less than the alternative solution:
/**
* Add lock
*/
Public Function File_lock ($filename) {
$fp _key = SHA1 ($filename);
$this->fps[$fp _key] = fopen ($filename, ' w+ ');
if ($this->fps[$fp _key]) {
Return Flock ($this->fps[$fp _key], lock_ex| LOCK_NB);
}
return false;
}
/**
* Unlock
*/
Public Function File_unlock ($filename) {
$fp _key = SHA1 ($filename);
if ($this->fps[$fp _key]) {
Flock ($this->fps[$fp _key], lock_un);
Fclose ($this->fps[$fp _key]);
}
}
Scenario 3: Discovery $redis->setnx () can provide the state of atomic operation: the same key executes SETNX after it has not expired or no del, and then execution returns false. This allows more than two concurrent requests to be controlled and must successfully acquire the lock to continue.
/**
* Add lock
*/
Public Function Task_lock ($taskid) {
$expire = 2;
$lock _key = ' task_get_reward_ '. $this->uid. ' _ '. $taskid;
$lock = $this->redis->setnx ($lock _key, Time ())//Set current times
if ($lock) {
$this->redis->expire ($lock _key, $expire); If 2s lock failure is not done
}
if (! $lock) {//If Get lock failure check time
$time = $this->redis->get ($lock _key);
if (Time ()-$time >= $expire) {//Add timestamp judgment in order to avoid expire execution failure, the deadlock can certainly be guaranteed with Redis's own transaction
$this->redis->rm ($lock _key);
}
$lock = $this->redis->setnx ($lock _key, Time ());
if ($lock) {
$this->redis->expire ($lock _key, $expire); If 2s lock failure is not done
}
}
return $lock;
}
/**
* Unlock
*/
Public Function Task_unlock ($taskid) {
$this->set_redis ();
$lock _key = ' task_get_reward_ '. $this->uid. ' _ '. $taskid;
$this->redis->rm ($lock _key);
}
The following setnx and expire operations can actually be used to ensure consistency with Redis transactions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.