Why? They all say that they are atomic. What I understand is Atomicity is either full commit or no commit, but I feel that this has nothing to do with concurrency. For example, when the first person uses incr, this time is 1, but it hasn't been completed yet. When the second person comes, he is still 1. At this time, the first bonus is 2... why? They all say that they are atomic. What I understand is Atomicity is either full commit or no commit, but I feel that this has nothing to do with concurrency. For example, when the first person uses incr, this time is 1 but it has not been completed yet. At this time, the second person is here, and he is still 1. At this time, the first addition is 2, and the second may be 2, I don't know what it means, right? Unless he locks the reader when he is the first user, and waits until the second user finishes reading it. Online and other experts can help me solve the problem ~
Reply content:
Why? They all say that they are atomic. What I understand is Atomicity is either full commit or no commit, but I feel that this has nothing to do with concurrency. For example, when the first person uses incr, this time is 1 but it has not been completed yet. At this time, the second person is here, and he is still 1. At this time, the first addition is 2, and the second may be 2, I don't know what it means, right? Unless he locks the reader when he is the first user, and waits until the second user finishes reading it. Online and other experts can help me solve the problem ~
To prevent concurrency problems, memcached provides the CAS (chech and save) method to obtain the corresponding value while obtaining the token (or version number) corresponding to the current key during get ), during the update operation, a token is required to compare the current token and whether it is consistent with the get operation. If it is inconsistent, the update fails. If other users operate on the current key, the token value changes.
The php reference code is as follows:
$cas = 0.0;do { $cnt = $m->get('cnt_key', null, $cas); if ($m->getResultCode() == Memcached::RES_NOTFOUND) { $m->add('cnt_key', 1); } else { $m->cas($cas, 'cnt_key', $cnt + 1); } } while ($m->getResultCode() != Memcached::RES_SUCCESS);
Note that the get method in the above Code has a $ cas parameter, which is the token corresponding to the current cnt_key. Once the cnt_key is operated, its value also changes. $ Cas value needs to be passed in the cas method. If the token changes, cas will fail to execute, that is, $ m-> getResultCode ()! = Memcached: RES_SUCCESS. So the loop body will be executed again.
This is done on the memcached client. For incr, the mechanism to ensure atomicity is completed on the memcached server. The principle should be similar to the above cas operation. Since the source code of memcached is not viewed, I dare not draw any conclusions.