在 glibc <= 2.23 中,为什么在 mutex_lock 宏中使用 `0;`?
In glibc <= 2.23, why is `0;` used in mutex_lock macro?
For glibc <= 2.23,看起来 malloc 的 mutex_lock
宏的通用定义使用 int
作为互斥量。 1
表示正在使用,0
表示免费。
它定义了这组通用宏:
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)
对于mutex_lock(m)
,0;
有什么作用?
表达式 ({ *(m) = 1; 0; })
是标准 C 的 GCC 扩展,称为 statement expression。它允许您在一个表达式中包含多个任意语句。
但是所有非空表达式都必须产生一个值,对于语句表达式
[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
所以最后的0;
就是表达式的结果。
For glibc <= 2.23,看起来 malloc 的 mutex_lock
宏的通用定义使用 int
作为互斥量。 1
表示正在使用,0
表示免费。
它定义了这组通用宏:
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)
对于mutex_lock(m)
,0;
有什么作用?
表达式 ({ *(m) = 1; 0; })
是标准 C 的 GCC 扩展,称为 statement expression。它允许您在一个表达式中包含多个任意语句。
但是所有非空表达式都必须产生一个值,对于语句表达式
[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
所以最后的0;
就是表达式的结果。