关于内核状态下的锁和用户空间的锁的介绍可以参考以下连接:
https://blog.youkuaiyun.com/lilichang11106/article/details/84069357
主要内容可以描述如下:
内核锁 | 用户锁 |
---|---|
spinlock_t | pthread_ spinlock_t |
mutex_t | pthread_mutex_t、pthread_rwlock_t |
struct semaphore | sem_t |
rwlock_t | pthread_ spinlock_t |
pthread_cond_t |
表格中每一行中的锁功能类似,具体定义,数据结构,初始化方法,开闭方法如上文中连接所示。
本文将给出实际的代码来实例如何使用锁保护资源。
内核锁的使用在内核驱动等模块,进程调度处理进程列表,中断下半部分任务列表等地方随处可见,这里就不做实例了。
首先我们来看看在linux用户空间使用spin_lock:
#include<string>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#define TEST_USER_SPIN_LOCK
#ifdef TEST_USER_SPIN_LOCK
#include<pthread.h>
pt