简体   繁体   English

互斥保护宏

[英]Mutex Protect Macro

This is one of my first posts on this community, so please bear with me. 这是我在该社区的第一篇文章之一,请耐心等待。

Is there a way to mutex protect a macro, in the macro itself. 有没有一种方法可以在宏本身中互斥保护宏。

For example, 例如,

#define FUNCTION_ \
doSomething()

Basically, I'm looking to do something like this 基本上,我想做这样的事情

#define FUNCTION_ \
mutex.lock \
doSomething() \
mutex.unlock

For further information, the macros are all declared within a header file, by themselves ( no namespace or class), which handles calls to an API. 有关更多信息,这些宏全部由它们自己的头文件(没有名称空间或类)声明,该头文件处理对API的调用。 We are utilizing C++. 我们正在使用C ++。 This header file is utilized by multiple projects therefore an overhaul of the macro itself is out of the question. 这个头文件被多个项目使用,因此宏本身的大修是不可能的。 For more detail on the Macro, it wraps calls to log4CXX.log4CXX is threadsafe; 有关宏的更多详细信息,它包装了对log4CXX的调用。log4CXX是线程安全的。 however, two threads utilizing this macro, who make a write call at the same time is not thread safe. 但是,使用此宏的两个线程同时进行写调用不是线程安全的。 Helgrind complains when running Valgrind about that. Helgrind在运行Valgrind时抱怨这一点。 Mutex protecting the macro in the code fixes the problem, but instead of mutex protection every single call, have the macro protect its own call. 互斥保护代码中的宏可以解决此问题,但是让宏保护自己的调用可以代替对每个调用的互斥保护。

If you have already this 如果您已经有这个

#define FUNCTION_ \
doSomething()

and if there is really no chance to stop such macro madness, then at least dont take it one step further. 如果真的没有机会阻止这种宏观的疯狂,那么至少不要再进一步了。 If you need a lock in doSomething() then the easiest would be to acquire the lock in the function: 如果您需要在doSomething()锁定,那么最简单的方法就是在函数中获取锁定:

void doSomething() {
    mutex.lock();
    /* .... */ 
    mutex.unlock();
}

or if for some reason you cannot change the function then wrap it 或者如果由于某种原因您无法更改函数,则将其包装

#define FUNCTION_ \
doSoemthingLocked()

void doSomethingLocked() {
    mutex.lock();
    doSomething();
    mutex.unlock();
}

(maybe declared as inline if you need to put it in a header, and maybe passing a reference to the mutex as parameter) (如果需要将其放在标题中,则可以声明为内联,并且可以将对互斥量的引用作为参数传递)

You have the code. 你有代码。 Just cover it up. 掩盖。 This should do: 应该这样做:

#define FUNCTION_ \
do { \
    mutex.lock() \
    doSomething() \
    mutex.unlock() \
} while(0)

The solution for the problem is as follows: 该问题的解决方案如下:

#define FUNCTION_ \
{ \
   mutex.lock(); \
   doSomething(); \
   mutex.unlock(); \
} \

However, for the mutex itself I have a mutex that wraps the pthread_mutex_t so in this situation I declared the mutex as: 但是,对于互斥锁本身,我有一个包裹pthread_mutex_t的互斥锁,因此在这种情况下,我将互斥锁声明为:

extern Mutex mutex; 互斥互斥体互斥;

Then in a .cpp file: 然后在.cpp文件中:

#include <headerFile.hpp>

Mutex mutex;

This creates a single instance of the mutex and prevents issues with multiple instances of the same name being discovered. 这将创建一个互斥锁实例,并防止发现多个同名实例的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM