# xv6 Spinloks lock 的兩大動作 * aquire/hold * release/free * 問題一: 有很多的 CPU 會 access 到相同的 memory * 解決方法: 使用個 lock 例如說: ```clike= if (lock == 0) hold(); else not_hold(); ``` Q: 個方法會產生問題,例如 A 跟 B 同時想要進入到這個 function,這個當下他們會認為現在這個 lock 是可以使用的 A: 使用 risc-v 的 `amoswap` Q: interrupt 以及 disable interrupt 的問題 * 進入 aquire 之後,再一次的 aquire 會產生問題 A: 所以希望它 aquire 之後,就不可以再一次 aquire 了,但是這還是會出現**另一個問題**(我也不太清楚XD) A: 所以最後就想到了要用 counter 的作法 也就是 `push()` 跟 `pop()` 的由來 ## 程式碼流程 ### implemention of spinlock: * `kernel/spinlock.h` ```clike= struct spinlock { uint locked; // Is the lock held? // For debugging: char *name; // Name of lock. struct cpu *cpu; // The cpu holding the lock. }; ``` * `kernel/spinlock.c` ```clike= void acquire(struct spinlock *lk) { push_off(); if(holding(lk)) // 如果這個 CPU 早就 hold 這個 lock 了 panic("acquire"); while(__sync_lock_test_and_set(&lk->locked, 1) != 0) ; __sync_synchronize(); lk->cpu = mycpu(); } ``` ### usage of spinlock: ```clike= aquire(); // critical section relea ``` ## 使用 lock 的原則 * 一個 lock 最好是 aquire 之後儘快的 release 掉 * 這樣才不會倒置其他 CPU 一直在等待 ## 參考資料 * [xv6 Kernel-4: Spinlocks](https://www.youtube.com/watch?v=gQdflOUZQvA&list=PLbtzT1TYeoMhTPzyTZboW_j7TPAnjv9XB&index=3)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up