Search code examples
cmallocc-preprocessorglibc

In glibc <= 2.23, why is `0;` used in mutex_lock macro?


For glibc <= 2.23, it looks like the generic definition of malloc's mutex_lock macro uses an int as a mutex. 1 means in use, and 0 means free.

It defines this generic set of macros:

typedef int mutex_t
# define mutex_init(m)          (*(m) = 0)
# define mutex_lock(m)          ({ *(m) = 1; 0; })
# define mutex_trylock(m)       (*(m) ? 1 : ((*(m) = 1), 0))
# define mutex_unlock(m)        (*(m) = 0)

For mutex_lock(m), what purpose does 0; serve?


Solution

  • The expression ({ *(m) = 1; 0; }) is a GCC extension to standard C, and it's called a statement expression. It allows you to have multiple arbitrary statements inside an expression.

    But all non-void expressions must result in a value, and for statement expressions

    [t]he last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct

    So the last 0; is simply the result of the expression.