简体   繁体   English

如何对数组使用增量?

[英]How to use increment with an array?

I know that it's possible to do something like that: 我知道可以做这样的事情:

$wgMemc->set( $key, 2, 60*30 );
$wgMemc->incr( $key );

but what if the numeric value is inside an array, like this?: 但是如果数值在数组内部,像这样呢?:

$wgMemc->set( $key, array( 'enabled' => $row->enabled, 'disabled' => 0 ), 60*30 );
$wgMemc->incr( ??? );

what is the best way to rave the same behaviour? 狂欢相同行为的最佳方法是什么?

You have to implement your own way of doing this. 您必须实现自己的方式。 Idea is simple: 1) Get the value by key 2) Make necessary updates to it (Increment, decrement, anything) 3) Set the new value for the key 想法很简单:1)通过键获取值2)对其进行必要的更新(递增,递减等)3)设置键的新值

However If you are in a concurrent environment (like any publicly available script) then between 1 and 3 someone else can access this part of your code. 但是,如果您处于并发环境中(如任何公共可用脚本),则其他人可以在1到3之间访问这部分代码。 Resulting in a simultaneous data updates. 导致同时进行数据更新。 This could end badly for you 这可能对您不利

So We have to make sure that only single user/process/thread is updating data at the moment. 因此,我们必须确保目前只有单个用户/进程/线程正在更新数据。 We can use locks for this. 我们可以为此使用锁。

Instead of 代替

$wgMemc->set( $key, array( 'enabled' => $row->enabled, 'disabled' => 0 ), 60*30 );
$wgMemc->incr( ??? );

let's add some locks there 让我们在那里添加一些锁

// acuire lock
$lock      = false;
$lock_ttl  = 10;
$tries     = 0;
$max_tries = 500;

// trying to obtain the lock. If we can't "add" the key - it means
// that someone else is updating data at the moment
// so we'll wait
while ( $tries < $max_tries && !($lock = $wgMemc->add("lock_" . $key, 1, $lock_ttl)) ) {
    $tries++;
    usleep( 100 * ($tries % ($max_tries/10)) );
}

// check if we successfully obtained the lock and then do our stuff
if ($lock) {
    $data = $wgMemc->get( $key );
    // update our data
    $data['enabled'] = 1;
    $data['blablabla']++;
    $wgMemc->set( $key, $data, 60*30 );
}

// release lock
$wgMemc->delete("lock_" . $key);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM