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.
if (!my_lock()) return <whatever>;
at the call sites, with a proper lock function. – Matpthread_mutex_lock
with uninitialized local variables. You don't need the variables at all actually, and I really recommend you think about what @Mat is saying, then you can have a single macro that is a simple expression. – Some programmer dude