OpenMP 临界区与锁

OpenMP critical section vs locks

OpenMP 锁和临界区有什么区别?他们只是彼此的替代品吗? 例如,如果我正在使用多个文件写入同一个文件,我应该在写入文件之前使用锁定还是只使用关键部分?

关键部分最常在内部使用锁,例如:

  • libgomp: source
  • libiomp:

    If the optional (name) is omitted, it locks an unnamed global mutex.

The OpenMP specification guarantees the following behaviour:

>

The critical construct restricts execution of the associated structured block to a single thread at a time

因此,临界区的作用与获取锁的作用相同。不同之处在于低级别的细节是为您处理的。

由于简单,我建议您尽可能使用 critical。如果您有单独的块,这些块需要是关键的但又不会相互干扰,请为它们命名,并且仅当您需要某些注释无法容纳的行为时,才使用显式锁定。