内核给数据加锁的例子
时间: 2023-08-12 21:19:14 浏览: 37
一个常见的内核给数据加锁的例子是使用自旋锁来保护共享数据结构。自旋锁是一种轻量级的锁,不会导致线程进入阻塞状态,而是一直忙等待(或“自旋”)直到锁被释放。
下面是一个简单的例子,假设有一个全局的共享计数器 count,多个线程需要同时对它进行读写操作:
```
#include <linux/spinlock.h>
static DEFINE_SPINLOCK(count_lock);
static int count = 0;
void increment_count(void) {
unsigned long flags;
spin_lock_irqsave(&count_lock, flags);
count++;
spin_unlock_irqrestore(&count_lock, flags);
}
int get_count(void) {
unsigned long flags;
int val;
spin_lock_irqsave(&count_lock, flags);
val = count;
spin_unlock_irqrestore(&count_lock, flags);
return val;
}
```
在上面的代码中,spin_lock_irqsave 和 spin_unlock_irqrestore 分别用于获取和释放自旋锁。这里使用了 IRQ 保存和恢复的版本,以确保在中断上下文中也能够正确使用锁。
需要注意的是,使用自旋锁需要保证临界区的代码执行时间尽可能短,否则会导致其他线程长时间等待,降低系统性能。