Instead of checking the value before incrementing, you can simply ADD it instead before incrementing each time. If it's already there, your ADD is ignored, and if it's not there, it's set.
If you add($memcacheKey, 0) and then increment($memcacheKey, 1) in that order, you avoid all possible race conditions. If two threads are running this code concurrently, you will always end up with your value being 2 no matter which order the threads execute in.Memcache::increment
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Memcache::increment
Референца за `memcache.increment.php` со подобрена типографија и навигација.
Memcache::increment
memcache_increment
(PECL memcache >= 0.2.0)
Memcache::increment -- memcache_increment — Зголеми ја вредноста на ставката
= NULL
$memcache, string $key, int $value = 1): int|false
Memcache::increment() ја зголемува вредноста на ставката за наведената value. Ако ставката наведена од
key не беше нумеричка и не може да се претвори во број, нејзината вредност ќе се промени во value.
Memcache::increment() Оваа функција
креирај ставка ако веќе не постои.
Забелешка: Пример #4 Користење именуван подшаблон Memcache::increment() со ставки што биле складирани компресирани бидејќи последователните повици до Memcache::get() ќе откаже.
Параметри
key- Клуч на ставката за зголемување.
value-
Зголеми ја ставката за
value.
Вратени вредности
Враќа нова вредност на ставката при успех или false при неуспех.
Примери
Пример #1 Memcache::increment() example
<?php
/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* increment counter by 2 */
$current_value = memcache_increment($memcache_obj, 'counter', 2);
/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* increment counter by 3 */
$current_value = $memcache_obj->increment('counter', 3);
?>Види Исто така
- Memcache::decrement() - Намали вредност на ставка
- Memcache::replace() - Отвора постојана врска со memcached серверот
Белешки од корисници 5 белешки
Please note:
If the key does not exist, memcache does NOT return false (as you might expect) but 0.
You won't get any hint that the key did not exist and still does not exist and that nothing was incremented.When the key doesn't exist it may return either bool(false) or int(0) (I get different return values on different servers), so be careful if you check for something like ($memcache->increment($key) === false).Be careful to use Memcache::decrement() and never Memcache::increment() with a negative value.
The check that prevents Memcache::decrement() from going negative is not in place with Memcache::increment(), so you can end up with a garbage integer on the order of 18 quintillion stored in place of the expected value.