请输入您要查询的百科知识:

 

词条 mutex
释义

基本概述

Mutex:/mjuteks/

互斥(体) 又称同步基元使用了System.Threading 命名空间。

当创建一个应用程序类时,将同时创建一个系统范围内的命名的Mutex对象。这个互斥元在整个操作系统中都是可见的。当已经存在一个同名的互斥元时,构造函数将会输出一个布尔值。程序代码通过检测这个布尔值来判断指定的程序实例是否启动,如果已经存在同名互斥元的话,则显示一个对话框,告知用户应用程序已经启动,并退出应用程序。

A data structure for mutual exclusion, also known as a binary semaphore. A mutex is basically just a multitasking-aware binary flag that can be used to synchronize the activities of multiple tasks. As such, it can be used to protect critical sections of the code from interruption and shared resources from simultaneous use.

表现互斥现象的数据结构,也被当作二元信号灯。一个互斥基本上是一个多任务敏感的二元信号,它能用作同步多任务的行为,它常用作保护从中断来的临界段代码并且在共享同步使用的资源。

mutex

场景

Mutex主要用于有大量并发访问并存在cache过期的场合,如

首页top 10, 由数据库加载到memcache缓存n分钟微博中名人的content cache, 一旦不存在会大量请求不能命中并加载数据库需要执行多个IO操作生成的数据存在cache中, 比如查询db多次

问题

在大并发的场合,当cache失效时,大量并发同时取不到cache,会同一瞬间去访问db并回设cache,可能会给系统带来潜在的超负荷风险。我们曾经在线上系统出现过类似故障

解决方法

方法一

在load db之前先add一个mutex key, mutex key add成功之后再去做加载db, 如果add失败则sleep之后重试读取原cache数据。为了防止死锁,mutex key也需要设置过期时间。伪代码如下

(注:下文伪代码仅供了解思路,可能存在bug,欢迎随时指出。)

if (memcache.get(key) == null)

{ // 3 min timeout to avoid mutex holder crash

if (memcache.add(key_mutex, 3 * 60 * 1000) == true)

{ value = db.get(key);

memcache.set(key, value);

memcache.delete(key_mutex);

} else

{ sleep(50);

retry();

}

}

方法二

在value内部设置1个超时值(timeout1), timeout1比实际的memcache timeout(timeout2)小。当从cache读取到timeout1发现它已经过期时候,马上延长timeout1并重新设置到cache。然后再从数据库加载数据并设置到cache中。伪代码如下

v = memcache.get(key);

if (v == null)

{ if (memcache.add(key_mutex, 3 * 60 * 1000) == true)

{ value = db.get(key);

memcache.set(key, value);

memcache.delete(key_mutex);

} else

{ sleep(50);

retry();

}

} else

{ if (v.timeout <= now())

{ if (memcache.add(key_mutex, 3 * 60 * 1000) == true)

{ // extend the timeout for other threads

v.timeout += 3 * 60 * 1000;

memcache.set(key, v, KEY_TIMEOUT * 2);

// load the latest value from db v = db.get(key);

v.timeout = KEY_TIMEOUT;

memcache.set(key, value, KEY_TIMEOUT * 2);

memcache.delete(key_mutex);

} else

{ sleep(50);

retry();

}

}

}

相对于方案一

优点:避免cache失效时刻大量请求获取不到mutex并进行sleep

缺点:代码复杂性增大,因此一般场合用方案一也已经足够。

方案二在Memcached FAQ中也有详细介绍 How to prevent clobbering updates, stampeding requests,并且Brad还介绍了用他另外一个得意的工具 Gearman 来实现单实例设置cache的方法,见 Cache miss stampedes,不过用Gearman来解决就感觉就有点奇技淫巧了。

随便看

 

百科全书收录4421916条中文百科知识,基本涵盖了大多数领域的百科知识,是一部内容开放、自由的电子版百科全书。

 

Copyright © 2004-2023 Cnenc.net All Rights Reserved
更新时间:2025/2/26 7:15:34