在OpenMP代码中使用C ++互斥锁是否安全?
在OpenMP 4.5代码中使用C ++ 11 std :: mutex
是否安全?我的想法是,我正在使用一个日志库,该日志库使用C ++互斥锁保护每个 std :: cout
,以便在与多个线程一起运行时,不会扰乱 cout
的输出.在我的OpenMP代码中,我可能想使用此日志记录库来打印一些消息.这样做安全吗?
Is it safe to use a C++11 std::mutex
inside OpenMP 4.5 code? The idea is that I am using a logging library which protects each std::cout
using a C++ mutex so that the outputs to cout
are not scrambled when running with multiple threads. Inside my OpenMP code I may want to use this logging library to print some messages. Is it safe to do so?
不,这不安全.
只有最新的OpenMP版本(5.0)才指定"与C ++ 11功能的交互.它是通过使用"C ++ 11库[...]可能导致未指定的行为"来表示的.
Only the very latest OpenMP version (5.0) even "specifies" the interaction with C++11 features. It does so by saying that using the "C++11 library [...] may result in unspecified behavior".
在实践中,这可能会很好地工作,但是在未指定行为的土地"上工作绝对不是可取的.您可能会发现超出标准的实现,并允许这种组合.
Practically, it may very well work, but working in "unspecified behavior land" is never desirable. You might find an implementation that goes beyond the standard and allows such combinations.
涉及互斥锁时,建议将其保留在一个范例中并使用OpenMP提供的互斥锁.
When it comes to mutexes, the recommendation it to stay within one paradigm and use the mutexes provided by OpenMP.