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.
This was the best I came up with:
Note that you have to use the rarely used comma operator and there are restrictions to what code can live within the (not quite java-like) synchronization code list.
Very interesting question!
I looked at the other answers and liked the one using
for
. I have an improvement, if I may! GCC 4.3 introduces the COUNTER macro, which we can use to generate unique variable names.Using those macros, this code...
... will expand to...
With my_mutex__n starting in 0 and generating a new name each time its used! You can use the same technique to create monitor-like bodies of code, with a unique-but-unknown name for the mutex.
Here's a start, but you may need to tweak it:
Use like this (unfortunately, not the Java-like syntax you wanted):
EDIT: Changed to nategoose's version
And you can use it like this:
Or even without braces