ldd3笔记——chapter5

并发与竞争

1.竞争情况的原因是来自对资源的共享存取的结果。加锁的目的在于,代码在任何时刻只会被一个进程所执行。

2.linux信号量

  为了使用semaphore内核代码必须包含头文件<asm/semaphore.h>

/* Please don't access any members of this structure directly */
struct semaphore {
	raw_spinlock_t		lock;
	unsigned int		count;
	struct list_head	wait_list;
};

#define DEFINE_SEMAPHORE(name)	\
	struct semaphore name = __SEMAPHORE_INITIALIZER(name, 1)

static inline void sema_init(struct semaphore *sem, int val)
{
	static struct lock_class_key __key;
	*sem = (struct semaphore) __SEMAPHORE_INITIALIZER(*sem, val);
	lockdep_init_map(&sem->lock.dep_map, "semaphore->lock", &__key, 0);
}
extern void down(struct semaphore *sem);
extern int __must_check down_interruptible(struct semaphore *sem);
extern int __must_check down_killable(struct semaphore *sem);
extern int __must_check down_trylock(struct semaphore *sem);
extern int __must_check down_timeout(struct semaphore *sem, long jiffies);
extern void up(struct semaphore *sem);

int down_interruptible(struct semaphore *sem)

down_interruptible输入参数说明

  • sem:信号量结构体指针,指向将要获取的信号量。其中,关于信号量结构体semaphore的说明参考极客笔记的sema_init()函数的分析说明。

down_interruptible返回参数说明

  • down_interruptible()函数返回一个整型值,如果成功获取了信号量,则返回0,否则在收到中断信号后,将返回-EINTR。

 

3.Reader/Writer Semaphores

struct rw_semaphore {
	atomic_long_t count;
	/*
	 * Write owner or one of the read owners as well flags regarding
	 * the current state of the rwsem. Can be used as a speculative
	 * check to see if the write owner is running on the cpu.
	 */
	atomic_long_t owner;
#ifdef CONFIG_RWSEM_SPIN_ON_OWNER
	struct optimistic_spin_queue osq; /* spinner MCS lock */
#endif
	raw_spinlock_t wait_lock;
	struct list_head wait_list;
#ifdef CONFIG_DEBUG_RWSEMS
	void *magic;
#endif
#ifdef CONFIG_DEBUG_LOCK_ALLOC
	struct lockdep_map	dep_map;
#endif
};

void init_rwsem(struct rw_semaphore *sem);
void down_read(struct rw_semaphore *sem);
int down_read_trylock(struct rw_semaphore *sem);
void up_read(struct rw_semaphore *sem);

4.completion
作用:允许一个线程告诉另一个线程工作已经完成。
<linux/completion.h>
struct completion {
	unsigned int done;
	struct swait_queue_head wait;
}
completion可以被静态创建:
DECLARE_COMPLETION(my_completion);

或者动态的创建:
struct completion my_completion;

init_completion(&my_completion);

等待completion:
wait_for_completion(struct completion *c);  //不可中断的等待

真正的comletion时间可能通过调用下列之一发出:
comlete(struct comletion *c)
comlete_all(struct compleion *c)//正常情况下只有一个等待者;


 
posted @ 2022-04-26 18:58  老胡同学  阅读(57)  评论(0)    收藏  举报