当前位置: C语言 -- 专题 -- 互斥类型的困惑

互斥类型的困惑

根据ISO/IEC 9899:2011标准第381页第7.26.4.2 The mtx_init function节,原文内容为:

  The mtx_init function creates a mutex object with properties indicated by type,
  which must have one of the six values:
  mtx_plain for a simple non-recursive mutex,
  mtx_timed for a non-recursive mutex that supports timeout,
  mtx_plain | mtx_recursive for a simple recursive mutex, or
  mtx_timed | mtx_recursive for a recursive mutex that suports timeout.

于是问题就产生了,互斥类型究竟是四种类型还是六种类型?


根据WG14 Document: N1372(Threads for the C Standard Library)文档第7The mtx_init function,原文内容为:

  The function creates a mutex object with properties indicated by type,which
  must have one of the six values:
    • mtx_plain—for a simple non-recursive mutex
    • mtx_timed—for a non-recursive mutex that supports timeout
    • mtx_try—for a non-recursive mutex that supports test and return
    • mtx_plain | mtx_recursive—for a simple recursive mutex
    • mtx_timed | mtx_recursive—for a recursive mutex that suports timeout
    • mtx_try | mtx_recursive—for a recursive mutex that suports test and return

这里提到了互斥类型的六种形式。


ISO/IEC 9899:2011标准第377页第7.26.1 Introduction节中定义了枚举常量mtx_plainmtx_recursivemtx_timed;并未定义mtx_try。查阅资料也发现,普遍认为C11标准的互斥类型为四种。

结论:ISO/IEC 9899:2011标准中的互斥类型应为四种,即mtx_plainmtx_timedmtx_plain | mtx_recursivemtx_timed | mtx_recursive;但在实现中也可能支持mtx_trymtx_try | mtx_recursive类型,例如:Visual Studio


ISO/IEC 9899:2018标准第292页第7.26.4.2 The mtx_init function节对该处作了修改,具体如下:

  The mtx_init function creates a mutex object with properties indicated by type,
  which shall have one of these values:
  mtx_plain for a simple non-recursive mutex,
  mtx_timed for a non-recursive mutex that supports timeout,
  mtx_plain | mtx_recursive for a simple recursive mutex, or
  mtx_timed | mtx_recursive for a recursive mutex that suports timeout.