Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

c - Possible to define a function-like macro with a variable body?

I've been looking at the GCC docs for defining macros and it looks like what I want isn't possible, but I figure if it is, someone here would know.

What I want to do is define this macro:

synchronized(x) {
  do_thing();
}

Which expands to:

{
    pthread_mutex_lock(&x);
    do_thing();
    pthread_mutex_unlock(&x);
}

In C++ I could just make a SynchronizedBlock object that gets the lock in its constructor and unlocks in the destructor, but I have no idea how to do it in C.

I realize I could use a function pointer in the form synchronized(x, &myfunction);, but my goal is to make some C code look as much like Java as possible. And yes, I know this is evil.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT: Changed to nategoose's version

#define synchronized(lock) 
for (pthread_mutex_t * i_#lock = &lock; i_#lock; 
     i_#lock = NULL, pthread_mutex_unlock(i_#lock)) 
    for (pthread_mutex_lock(i_#lock); i_#lock; i_#lock = NULL)

And you can use it like this:

synchronized(x) {
    do_thing(x);
}

Or even without braces

synchronized(x)
    do_thing();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...