Concurrentcy Knowledge
Concurrentcy : multi-units get or modify a same critical region in parallel, which can cause a race condition. it can be
1) mutli-core CPU
2) interrupt & process/thread
3) single CPU but preemptive process/thread
#编译乱序 (由编译器所决定)
可增加barrier()来防止。
#执行乱序 :没有按照编译好的指令次序执行,由CPU所决定,如cache, 访问阻塞,多核等原因造成
在多核的系统,一段代码中由一部分可以在一个CPU0执行,而另外一部分代码可以在CPU1上执行。这样就不能保证代码按预期顺序执行。
处理器为了处理由于多核间一个核的内存行为对另外一个核可见的问题,引入了内存屏障的指令(这一段时间另外一个核不可见)。DMB(), DSP(), ISB().
当我们要访问外部的寄存器的时候需要顺序执行,这时候也需要内存屏障指令。Linux 已经进行了封装如readb(), writeb()等操作。
Mutex provides one person to access a single resource at a time, others must wait in a queue. Once this person is done, the guy next in the queue acquires the resource.
So access is serial, one guy after another. There is a context switch of the requester thread if the mutex is unavailable.
Semaphore is useful if multiple instances (N) of a resource are shared among a set of users. As soon as all N resources are acquired, any new requester has to wait. Since there is no single lock to hold, there is as such no ownership of a semaphore.
Spinlock is an aggressive mutex. In mutex, if you find that the resource is locked by someone else, you (the thread/process) switch the context and start to wait (non-blocking).
Whereas spinlocks do not switch context and keep spinning. As soon as the resource is free, they go and grab it. In this process of spinning, they consume many CPU cycles. Also, on a uni-processor machine, they are useless and perform very badly.
DIFFERENCE BETWEEN SPINLOCK AND MUTEX
|
|
||
| Used when the task can sleep while waiting for the lock. | Used when the task can’t sleep while waiting for the lock. | ||
| It can be held for a long duration of time. | It can be held for a short duration of time. | ||
|
It can only be used in process context, not in interrupt context. copy_from_user, copy_to_user, msleep, kmalloc |
It can only be used in the Interrupt context, not in the Process context. | ||
| High overhead locking. | Low overhead locking. |
浙公网安备 33010602011771号