问题描述
要在内核v4.19-rc5中初始化自旋锁,必须使用如下定义的spin_lock_init
宏:
To initialize a spinlock in kernel v4.19-rc5 one must use the spin_lock_init
macro defined as follows:
#define spin_lock_init(_lock) \
do { \
spinlock_check(_lock); \
raw_spin_lock_init(&(_lock)->rlock); \
} while (0)
函数spinlock_check(_lock)
仅返回&lock->rlock
. 这篇文章说明:
The function spinlock_check(_lock)
just return &lock->rlock
. This article explains that:
我不明白此功能如何执行检查.我期望在ckeck函数中有一些if
语句.抱歉,我是内核编程的新手.
I dont't understand how this function performs a check. I was expecting some if
statements in a ckeck function. I'm sorry but I'm new to kernel programming.
推荐答案
它不需要任何if
语句,因为它用于编译时检查.
It doesn't need any if
statements because it exists for compile time checking.
您可以在大多数情况下看到此处操作被定义为宏,因此它们无法限制其参数的类型.
You can see here that most spinlock operations are defined as macros, so they are not able to restrict type of their argument.
请考虑以下示例:
struct not_a_spinlock {
raw_spinlock_t rlock;
};
如果没有spinlock_check
,我可以使用spin_lock_init
对其进行初始化:
Without spinlock_check
I could use spin_lock_init
to initialize it:
struct not_a_spinlock spin;
spin_lock_init(&spin);
但是由于spinlock_check
,这将无法正常工作.这使这些宏具有类型限制,因此它们的行为更像函数.
But thanks to spinlock_check
, this will not work. This makes those macros type-restricted so they act more like functions.
它返回&lock->rlock
的原因是为了方便-它的返回值可以传递给下一个函数.
The reason it returns &lock->rlock
is due to convenience - its returned value can be passed to the next function.
因此值得从您的示例中将宏重写为:
So it could be worth rewriting the macro from your example as:
#define spin_lock_init(_lock) \
do { \
raw_spin_lock_init(spinlock_check(_lock)); \
} while (0)
类似的技术可以与宏一起使用,以在某种程度上限制其参数类型,例如:
#define min(x, y) ({ \
typeof(x) _min1 = (x); \
typeof(y) _min2 = (y); \
(void) (&_min1 == &_min2); \
_min1 < _min2 ? _min1 : _min2; })
这篇关于自旋锁初始化功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!