I have created the following macros to lock a mutex and return (from the function within which this macro is called) in case the attempt at locking fails. Currently I have narrowed it down to 2 macros - one for returning from functions which do return a value, irrespective of type, and another for returning from functions which return nothing (i.e. void).
The code beyond the macros (below) is for illustration only and has very little to do with the actual production code that the macros will be used in.
#define MUTEX_LOCK()\
{\
if (pthread_mutex_lock(&mutex) != 0)\
{\
printf("Failed to lock mutex.\n");\
return;\
}\
}
#define MUTEX_LOCK_RVAL(err_val)\
{\
if (pthread_mutex_lock(&mutex) != 0)\
{\
printf("Failed to lock mutex.\n");\
return err_val;\
}\
}
void vfunc()
{
printf("\nIn vfunc()\n");
MUTEX_LOCK();
printf("\nOut of vfunc()\n");
}
UINT16 uint16func()
{
printf("\nIn uint16func()\n");
MUTEX_LOCK_RVAL(0);
printf("\nOut of uint16func()\n");
return 9;
}
CHAR* errstr = "Hoo boy!";
CHAR* strfunc()
{
printf("\nIn strfunc()\n");
MUTEX_LOCK_RVAL(errstr);
printf("\nOut of strfunc()\n");
return NULL;
}
Is there a way to reduce these to a single macro that can be used in functions returning a value as well as void.
Macros just perform textual substitution. They can't return anything - they are not functions.
A macro that returns a value must have exactly one statement that either is not a macro syntax statement, or is a macro syntax statement that returns a value into the processing stream. %sysfunc is an example of a statement that does so. Things like %let , %put , %if , etc.
Speed versus size The main benefit of using macros is faster execution time. During preprocessing, a macro is expanded (replaced by its definition) inline each time it is used. A function definition occurs only once regardless of how many times it is called.
To make it ANSI compatible I define the macro with return and another simple symbol that evaluates to null and is clearly showing that it is null. I.e.:
#define VOID_RET //This nulls the return value
#define MUTEX_LOCK(err_val)\
{\
if (pthread_mutex_lock(&mutex) != 0)\
{\
printf("Failed to lock mutex.\n");\
return err_val;\
}\
}
void *mutex = NULL;
void vfunc(void)
{
printf("\nIn vfunc()\n");
MUTEX_LOCK(VOID_RET);
printf("\nOut of vfunc()\n");
}
UINT16 uint16func(void)
{
printf("\nIn uint16func()\n");
MUTEX_LOCK(0);
printf("\nOut of uint16func()\n");
return 9;
}
CHAR* errstr = "Hoo boy!";
CHAR* strfunc(void)
{
printf("\nIn strfunc()\n");
MUTEX_LOCK(errstr);
printf("\nOut of strfunc()\n");
return NULL;
}
I tested this code under C11 and C99.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With