原文转自:http://www.hellodb.net/2010/06/oracle-mutex.html   http://blog.csdn.net/tianlesoftware/article/details/6455517

在这篇文章里,提到了System Locks,它包含:

(1)Latches

(2)Mutexes

(3)Internal Locks

一.  官方文档上关于Mutex 的说明如下

Mutexes

A mutual exclusion object (mutex) is a low-level  mechannism that prevents an object in memory from aging(老化) out or from being corrupted when accessed by concurrent processes. A mutex is similar to a latch(和latch类似), but whereas(然而) a latch typically protects a group of objects, a mutex protects a single object.(一个latch保护一组对象,一个mutex保护一个对象)

Mutexes provide several benefits:

(1)A mutex can reduce the possibility of contention.

Because a latch protects multiple objects, it can become a bottleneck when processes attempt to access any of these objects concurrently. By serializing access to an individual object rather than a group, a mutex increases availability.(mutex有效的减少了竞争,因为latch保护的是多个对象,在访问这些对象的时候就会形成瓶颈,但是mutex只保护一个对象,这样大大提高了资源可用性)

(2)A mutex consumes less memory than a latch.(mutex占用的内存资源比latch少)

(3)When in shared mode, a mutex permits concurrent reference by multiple sessions.(共享模式下的mutex,允许并发进程访问数据)

二.  eygle 的blog上搜的信息

Mutex 的发音是 /mjuteks/ ,其含义为互斥(体),这个词是Mutual Exclude的缩写。

Mutex在计算机中是互斥也就是排他持有的一种方式,和信号量-Semaphore有可以对比之处。有人做过如下类比:

Mutex是一把钥匙,一个人拿了就可进入一个房间,出来的时候把钥匙交给队列的第一个。一般的用法是用于串行化对critical section代码的访问,保证这段代码不会被并行的运行。

Semaphore是一件可以容纳N人的房间,如果人不满就可以进去,如果人满了,就要等待有人出来。对于N=1的情况,称为binary semaphore。一般的用法是,用于限制对于某一资源的同时访问。

对于Binary semaphore与Mutex,这两者之间就存在了很多相似之处:

在有的系统中Binary semaphore与Mutex是没有差异的。

在有的系统上,主要的差异是mutex一定要由获得锁的进程来释放。而semaphore可以由其它进程释放(这时的semaphore实际就是个原子的变量,大家可以加或减),因此semaphore可以用于进程间同步。

Semaphore的同步功能是所有系统都支持的,而Mutex能否由其他进程释放则未定,因此建议mutex只用于保护critical section。而semaphore则用于保护某变量,或者同步。

最近有客户在Oracle10gR2上遇到了Mutex竞争的问题。

Mutex是Oracle在Oracle10g中引入的串行机制,逐渐会用来替代一些存在性能问题的Latch。
和Latch相比,一个Mutex Get大约仅需要30~35个指令,而Latch Get则需要大约150~200个指令,同时在大小上,每个Mutex仅占用大约16 Bytes空间,而一个latch在10gR2中要占用大约112 Bytes空间。

Mutex首先替代了Library Cache Latch以及Library Cache Pin,在Oracle 10.2.0.2上通过隐含参数_kks_use_mutex_pin的调整可以限制是否使用Mutex机制来实现Cursor Pin:

SQL> set linesize 120
SQL> col name for a30
SQL> col value for a20
SQL> col describ for a60
SQL> SELECT x.ksppinm NAME, y.ksppstvl VALUE, x.ksppdesc describ
  2    FROM SYS.x$ksppi x, SYS.x$ksppcv y
  3  WHERE x.indx = y.indx
  4    AND x.ksppinm LIKE '%&par%'
  5  /
Enter value for par: mutex
old  4:    AND x.ksppinm LIKE '%&par%'
new  4:    AND x.ksppinm LIKE '%mutex%'

NAME                    VALUE                DESCRIB
------------------ -------------- ------------------------------------------------------------
_kks_use_mutex_pin      TRUE            Turning on this will make KKS use mutex for cursor pins.

在新的Mutex Pins机制下,以下等待事件可能变得常见:
cursor: mutex S
cursor: mutex X
cursor: pin S
cursor: pin S wait on X
cursor: pin X 

由于Mutex使用CAS(Compare and Swap)机制,所以在不支持CAS的HP Unix平台上就可能出现CPU消耗过高的情况。
这作为一个Bug在10.2.0.4版本中被修正。

Data 1:

things get more fun in 10.2, you can pin cursors without getting library cache pin latch, using KGX mutexes. Mutexes are new in 10.2 and they enable shared access to objects in somewhat similar manner to shared latche; every successful get of a particular mutex will increment its value and a release will decrement. When the count is zero, no one has the mutex and it is safe to get it in exclusive mode. However, they are more fine-grained than kgl latches and provide a better wait mechanism, as far as I understand. 
            So if your environment supports atomic compare and swap operation (such as CMPXCHG on Intel), you might get away without cursor_space_for_time setting for ultrahigh execution rates. Otherwise the atomic mutex operations would be achieved using the new KGX latches.

At least on my laptop this feature isn't enabled by default (from an OracleWorld paper I remember that it should become default in 10.2.0.2), but so far you can experiment with it if you set _kks_use_mutex_pin = true and bounce the instance (mutex structures will be stored in the shared pool, so you might need to increase shared pool size).

There are also X$MUTEX_SLEEP and X$MUTEX_SLEEP_HISTORY fixed tables that can show some interesting information if you generate some mutex waits into them.

Data 2:

Mutex is the short form mutual exclusion object. A mutex, similar to a latch, is a low-level serialization mechanism used to control access to a shared data structure in the SGA.

2.1 Serialization is required to avoid an object being:

(1) Deallocated while someone is accessing it

(2) Read while someone is modifying it

(3) Modified while someone is modifying it

(4) Modified while someone is reading it

2.2 Mutexes can be defined and used in different ways, as in the following examples:

(1)Each structure being protected by a mutex can have its own mutex (for example, a parent cursor has its own mutex, and each child cursor has its own mutex)

(2)Each structure can be protected by more than one mutex, with each mutex protecting a different part of the structure.

(3) A mutex can protect more than one structure.

2.3 Although mutexes an latches are both serialization mechanisms, mutexes have certain features that latches do not:

(1)Smaller and Faster

Mutexes are an alternative to latches because they are smaller and much faster to get. A mutex get uses fewer instructions compared to a latch get. A mutex takes less memory space compared to a latch.

(2) Less Potential for False Contention

Latch typically protect multiple objects. When a latch protects one or more hot objects, the latch itself can become a serialization point when accessing any of the objects protected by that latch. This can be a false contention point, where the contention is for the protection mechanism (that is, latch), rather than the target object you are attempting to access. Unlike latches, with mutexes it is possible to create mutex for each structure protected. This mean that false contention is much less likely because each structure can be protected by its own mutex.

(3)Replace Latches and Pins

A mutex can be concurrently referenced by many sessions, providing all sessions reference the mutex in S (Shared) mode. The total number of sessions referencing a mutex in S mode is called the reference count ("ref count"). The ref count for a mutex is stored within the mutex itself. A mutex can also be held in X (eXclusive) mode by one session only.

Mutexes have a dual nature; they can act as a serialization mechanism (for example, latch) and also as a pin (for example, preventing an object from aging out).             For example, the ref count of a mutex is a replacement for a library cache pin. Instead of each session creating and then deleting a library cache pin when executing a cursor, each session increments and decrements the ref count (so the ref count replace n distinct pins).

Note: Latches and mutexes are independent mechanisms, that is, a process can hold a latch and a mutex at the same time.

2.4  Mutex operations are faster and have less contention than latches, but mutex operations still have waits associated with them. Two V$ view provide detail of mutex sleeps:

(1)V$MUTEX_SLEEP shows a summary of sleeps and wait time for particular mutex_type/location combination.

SQL>select * from v$mutex_sleep;

MUTEX_TYPE                   LOCATION                                  SLEEPS         WAIT_TIME

-------------------------------- ---------------------------------------- ---------- ----------

Cursor Stat                 kksIterCursorStat [KKSSTALOC6]      103 163

Cursor Stat                 kksFindCursorStat [KKSSTALOC3] 23157 36724

Cursor Parent            kksfbc [KKSCHLCREA]                        1799 10170

Cursor Parent             kkspsc0 [KKSPRTLOC27]                   26 627

Cursor Parent            kkspsc0 [KKSPRTLOC26]                  122 2872

Cursor Parent            kkshbbr [KKSPRTLOC15]                   660 1779

Cursor Parent            kksLoadChild [KKSPRTLOC4]             1181 6932

Cursor Parent             kksfbc [KKSPRTLOC2]               9006 34053

Cursor Parent            kksfbc [KKSPRTLOC1]                2831 144439

Cursor Pin                   kksLockDelete [KKSCHLPIN6]         5021 1055990

Cursor Pin                   kkslce [KKSCHLPIN2] 265549          2792810468

Cursor Pin                   kksfbc [KKSCHLPIN1]                     1203 5132409

Cursor Pin                  kksfbc [KKSCHLFSP2]               9279 56902065

(2)V$MUTEX_SLEEP_HISTORY show sessions sleeping for a particular mutex_type/location combination by time while it is held by a specific holding session.

2.5 Mutex wait event have two categories:

(1)cursor:mutex indicates that the mutex waits on parent cursor operations and statistics block operations.

(2)cursor:pin events are wait for cursor pin operations, where a mutex has replaced the latch:library cache pin.

2.6 Mutex wait events are of two types

(1)Short-duration events that should rarely be seen. These occur when one process attempts to update the mutex while it is being changed by another process. The waiting process will spin waiting for the mutex to be available. For example, cursor:pin S is incremented when another process is updating the reference count(pin) of shared cursor.

(2) Long-duration events occur when a process must wait for other processes to finish their operation. For example, cursor:mutex X is incremented when a process wants an exclusive access but the mutex is being held exclusive or shared by another process.

2.7 Mutex-Protected Operations:

A mutex is another protection mechanisms that can protect critical operations. From Oracle database V. 10.2.0.2 and later, a SELECT from the V$SQLSTATS view is protected by mutexes. The use of mutex-protected operations is significantly faster than latched operations. The child cursor lists are protected by mutexes.

我们都知道Latch是Oracle用来在内存中做串行控制的机构,从10g R2开始,Oracle引入了一个新的技术-Mutex。Mutex并不是Oracle的发明,而是系统提供的一个底层调用,Oracle只是利用它实现串行控制的功能,并替换部分Latch。

Mutex中有两个变量:分别是Holider identifer和Reference count,Holider identifer记录持有mutex的SID,而Reference count是一个计数,记录了当前正在以share方式访问mutex的数量,每当session以share方式持有mutex时,计数会加1,而释放时会减1。如果Reference count大于零,则表示该内存结构正在被Oracle pin住。

我们看一段伪代码,演示mutex的申请过程:

Function Mutex_get(mutex_name)
{if mutex.holder:=SIDcase mode:'exclusive':if mutex.ref_count=0return TRUEelsemutex.holder.clear;reture FALSEend if'share':mutex.ref_count++mutex.holder.clearreturn TRUEend caseelsereture FALSEend if
}

Mutex是如何实现串行控制的,实际上它是利用了操作系统的一个原子操作CAS(compare-and-swap)实现的。我们看到函数的开始处:mutex.holder:=SID,将SID赋值给mutex的Holider Identifer,这里就是一个原子的CAS操作,首先比较mutex.holder是否为空,如果不为空则赋值session的SID。CAS操作由OS来保证其原子性,在同一时刻这个操所是串行的。如果这个赋值操作失败,整个申请过程失败。赋值成功后,如果是share方式,则mutex.ref_count加1,并清空mutex.holder,如果是exclusive方式,需要判断mutex.ref_count是否为零(是否被pin住),如果大于0,则失败,并清空mutex.holder,如果等于0,则成功,这时不清空mutex.holder,保持当前session对mutex的exclusive占用,直到释放为止。

Mutex相比latch带来了以下的好处:

1.更少的资源消耗,mutex与latch不同,它不是独立存在的,而是在每个内存结构中,并随着内存结构创建和释放,mutex同时也被创建和释放。mutex暂用的空间比latch小很多,创建和释放消耗更少的资源。

2.有效降低竞争,因为mutex是每个内存结构中的一部分,这样意味着mutex的数量可以有很多,而不同于latch,一个latch需要管理很多个内存结构,当你访问同一latch管理的不同内存结构时,也会发生竞争,而mutex则不会。另外,因为latch的数量有限,很多时候latch本身的竞争会很厉害,之前,我们只能增加latch数量或者减少latch持有的时间,而现在,mutex是一个更好的选择。

3.更快的pin,当block被访问时,它必须被pin在buffer cache中,当一个cursor执行时,它也必须被pin在library cache中,如果大量并发频繁执行同一个cursor,library cache pin会耗费大量的CPU资源。而mutex使用reference count来解决并发访问的问题,只要它大于零,就表示它已经被pin在了内存中,不能被交换出去。而且mutex.ref_count++这个操所是非常快的,只占用非常少的资源。

Mutex申请的过程和latch类似,同样需要spin和sleep,不同的是Oracle硬编码了mutex spin的次数为255次(Latch spin的次数默认为2000,由隐含参数_spin_count控制)。latch sleep会随着等待次数的逐步增加,每次sleep的时间也会逐步增加。而mutex sleep则比较特别,它有三个选项,分别是yield CPU,sleep或者block other process,允许开发人员来决定采用哪种选项。

由于在某些RISC的操作系统中(HP-UNIX),由于系统不支持CAS操作,Oracle通过创建一个latch pool来模拟了CAS操作,被称为KGX latch,如果你发现系统中存在这种latch竞争,说明操作系统不支持CAS操作,可以通过_kks_use_mutex_pin关闭mutex。

mutex主要使用在library cache中,用来取代原来的library cache pin和library cache lock,关于library cache中锁的实现机制,我会在另外一篇文章中说明。

Library cache内部机制详解Oracle数据库性能模型
  1. jametong

    6 17th, 201020:48

    回复 | 引用 | #1

    在Oracle中, Mutex是一个类似于Lock的机制, 与Latch还是有较大的差异, Mutex有锁资源管理, 只是更加轻量级, latch类似于OS的spin_lock机制, 基本的操作类似于Compare and swap (或者Test and Set), 只是在内存中由Oracle进行控制(本人估计可能是为了避免进行过多的Kernel mode/user Mode的切换).

  2. jacky

    6 17th, 201022:18

    回复 | 引用 | #2

    latch是oracle自己实现的,mutex则是OS的系统调用,CAS的原子性是OS提供的,Oracle利用了它的特性。

  3. 八神

    6 19th, 201019:01

    回复 | 引用 | #3

    lock是一个排队机制,MUTEX应该还是和latch的机制差不多,只不过他更加轻量级,并且是通过资源本身上的count标志位来确定能否互斥,oracle的TX lock虽然也是用一个bit位来确定资源是否锁定,但是他需要维护排队信息,还是需要额外的resource的

  4. jacky

    6 19th, 201023:25

    回复 | 引用 | #4

    mutex是更轻量级的latch,而lock是由enqueue实现的,而enqueue这个结构又是靠latch保护起来的:)

  5. jametong

    6 21st, 201014:25

    回复 | 引用 | #5

    确实记错了啊.. 不过Mutex是os的系统调用吗?

  6. logchild

    6 21st, 201018:02

    回复 | 引用 | #6

    mutex在innodb中也大有所用

  7. jacky

    6 22nd, 201017:34

    回复 | 引用 | #7

    准确点说,mutex不是系统调用,而是用系统调用实现的,CAS在很多OS上都有现成的系统调用,由OS来保证其原子性。

  8. P.Linux

    7 3rd, 201022:42

    回复 | 引用 | #8

    Mutex是操作系统为了实现PV操作提供的原子功能,P/V两个操作都必须是原子的,才能保证并发不被打乱,与其相似的还有信号量Semaphore,这些都是操作系统原理上的东西了

Oracle Mutex实现机制相关推荐

  1. Oracle的latch机制源代码解析——借postgresql猜测Oracle的latch

    由于我手里并没有Oracle的源代码(而兄弟伙又未必敢冒着进去的风险把手里的源代码给我看),所以只能借用postgresql来分析一下Oracle的latch机制了(为什么是latch而不是mutex ...

  2. oracle 多版本机制,关于oracle多版本机制副作用的问题-Oracle

    我们已经知道oracle多版本机制能够提供一致性的答案,而且还有高度的并发性.但是真的就没有其他不好的一面吗? 案例1: 假设有一个资源调度程序(可以用来调度会议室,投影仪等资源),业务规则是:在给定 ...

  3. MySQL redo log 重做日志 原理 Oracle Redo Log 机制 小结

    MySQL-重做日志 redo log -原理 [redo log buffer][redo log file]-原理 目录: 1.重做日志写入过程图 2.相关知识点汇总图 3.redo_log_bu ...

  4. oracle游标等待,Oracle Mutex 等待事件之: cursor mutex X

    Oracle Mutex 等待事件之: cursor mutex X Cursor Mutex X 是当会话对某个 Cursor 请求排他模式锁,但是该Cursor 上已经有 S 或 X 模式的锁定, ...

  5. Oracle GoldenGate 系列:深入理解 Oracle GoldenGate 检查点机制

    检查点将进程的当前读写位置存储在磁盘中用于恢复目的.检查点不仅可以真实地标记 Extract进程捕获的要进行同步的数据变化以及 Replicat进程应用到 target数据库的数据变化,防止进程进行冗 ...

  6. ORACLE的工作机制

    我们从一个用户请求开始讲,ORACLE的完整的工作机制是怎样的,首先一个用户进程发出一个连接请求,如果使用的是主机命名或者是本地服务命中的主机名使用的是机器名(非IP地址),那么这个请求都会通过DNS ...

  7. Oracle Mutex 机制 说明

    之前也整理过一篇文章来说明Oracle Lock的,参考: 锁 死锁 阻塞 Latch 等待 详解 http://blog.csdn.net/tianlesoftware/archive/2010/0 ...

  8. 万字长文深入探究Oracle DML锁机制

    点击上方"蓝字" 关注我们,享更多干货! 1.1. 锁的基本概念 锁的定义:锁(lock)机制用于管理对共享资源的并发访问,用于多用户的环境下,可以保证数据库的完整性和一致性.锁是 ...

  9. oracle更改密码机制,Oracle密码机制以及常用操作

    Oracle 默认有3个用户: sys 密码:自定:system 密码:自定 :scott 密码:Tiger(默认锁定):注:用Sys用户登录须根 [as sysdba Oracle 默认有3个用户: ...

最新文章

  1. IMLS:用于3D重构的深层隐式移动最小二乘函数(CVPR2021)
  2. 人脸识别进校园引争议 “人工智能+教育”应审慎
  3. SQL Server审计功能入门:CDC(Change Data Capture)
  4. json web token 实践登录以及校验码验证
  5. OVS DPDK--数据结构关系(七)
  6. AAAI-2020 || 52篇深度强化学习accept论文汇总
  7. PESCMS Ticket 客服工单系统 v1.2.4 发布
  8. J2EE搭建Dynamic web SpringMVC工程404错误分析(二)
  9. html 树形图可拖拽,HTML5拖拽API实现vue树形拖拽组件
  10. 在linux下使用wine安装photoshop cs6
  11. 【Python】字符串反转
  12. HTML页面多个平行四边形,平行四边形奥数题
  13. 我读研期间通过实习和比赛收入五十万
  14. 苹果Mac高级文件搜索工具:ProFind
  15. Linux内核解读入门(转CSDN)
  16. 远心镜头(Telecentric lens)原理介绍
  17. 时间 java 时间段_Java 如何判断当前时间是否在指定时间段内
  18. vc编程的ime输入法菜单开发
  19. html四种选择器的特点,css四种选择器总结
  20. 飞利浦、TCL、海信、REASONANCE、七彩虹、Amazfit在CES展示最新新品 | 美通企业日报...

热门文章

  1. TPO Official 53 Independent Writing Task
  2. echarts 添加百分号%
  3. RE合同记账会计凭证
  4. pyinstaller打包遇到MatplotlibDeprecationWarning问题
  5. 国内CRM竞品分析【纷享销客 VS 销售易 VS 用友】
  6. 计算机组成-无符号数乘法
  7. 【图像分类案例】(10) Vision Transformer 动物图像三分类,附Pytorch完整代码
  8. 首席新媒体黎想教程:线上活动推广执行手册——第二篇
  9. Java Web高级面试题(二)
  10. 入手评测 小度智能学习平板S12 怎么样