使用 GCC 4.8.2(在 Linux/Debian/Sid 64 位上)-或 GCC 4.9(如果可用)-在 C++11 中-我有一些互斥体
std::mutex gmtx;
actually, it is a static
member in some class Foo
containing both alpha
and beta
methods below.
它被锁在alpha
like
void alpha(void) {
std::lock_guard<std::mutex> g(gmtx);
beta(void);
// some other work
}
我想办理入住手续beta
确实如此gmtx
被锁住了:
void beta(void) {
assert (gmtx.is_locked());
// some real work
}
(notice that is_locked
is only called inside assert
... It can be very inefficient or even sometimes inaccurate)
当然,我还有其他函数调用beta
, e.g.
void gamma(void) {
std::lock_guard<std::mutex> g(gmtx);
beta();
// some other work
}
but is_locked
不存在....我该如何定义它? (实际上我想确保互斥体已被某些[间接]调用者锁定在同一线程中......)
(我想测试它的原因assert
就是它beta
可以在其他地方调用)
我无法使用try_lock
(除非使用递归互斥体),因为在常见情况下,它会锁定已经锁定的互斥体...(由调用者锁定在同一线程中),这不仅是未定义的行为,而且完全阻塞。
我想避免递归互斥体(比普通互斥体成本更高),除非我真的必须这样做。
NB: The real program is a bit more complex. Actually, all the methods are inside a class which maintain a naming bi-directional relation on "items". So I have inside that class a map from items to names and another from names to items. beta
would be the internal method adding really a naming, and alpha
and gamma
would be the methods finding -or adding- an item by its name, or a name by its item.
PS: the real program is not yet released, but should become part of MELT http://gcc-melt.org/ - its future monitor http://gcc.gnu.org/ml/jit/2013-q4/msg00025.html; you can download it (alpha stage, very buggy) from here http://starynkevitch.net/Basile/monimelt-19feb2014.tgz (a temporary location)