§ Semaphores
1.Overview
Binary semaphores: Synchronization
-
申请、和释放由不同的任务执行。
-
Caveat: if the event repeats too quickly, information may be lost.
Mutual exclusion semaphores: Mutual Exclusion
-
有owner的概念。
-
申请和释放由同一个任务(owner)执行。
-
一个任务可以申请多次。
-
只有owner才可以释放。
Counting semaphores
2.More about Mutual exclusion semaphores
Deletion Safety (owner exists)
-
The deletion safety option prevents a task from being deleted while it owns the semaphore.
-
SEM_DELETE_SAFE options
-
STATUS taskDeleteForce (tid)
Unbounded Priority Inversion
-
Problem exists
-
Priority inheritance algorithm solves the unbounded priority inversion problem.
-
Enabled on mutex semaphores by specifying the SEM_INVERSION_SAFE option during semMCreate( ).
编程建议
-
编写访问资源的库函数
-
在库函数中使用互斥机制
-
用户只通过库函数访问资源
Deadlock Problem
-
Problem description
-
Solutions: 1) 只使用一个信号量保护资源, 2) 所有任务按照相同的顺序访问资源
其他注意事项
-
不能在ISR 中使用;
-
Critical region 尽量短;
Locking Out Preemption
-
When doing something quick frequently, it may be preferable to disable preemption instead of taking a mutex.
-
Does not disable interrupts.
-
taskLock( )/taskUnlock( ) is faster than semGive( )/semTake( ).
ISR’s and Mutual Exclusion (ISR VS. Task)
-
ISR’s can’t use mutex semaphores.
-
Task sharing a resource with an ISR may need to disable interrupts.
-
To disable/re-enable interrupts: int intLock( ), void intUnlock (lockKey)