lock()
除非您有其他复印理由,否则请使用。仅当您以不同的顺序请求多个锁时,才会发生死锁,例如:
线程 1:
lock(A) {
// .. stuff
// Next lock request can potentially deadlock with 2
lock(B) {
// ... more stuff
}
}
线程 2:
lock(B) {
// Different stuff
// next lock request can potentially deadlock with 1
lock(A) {
// More crap
}
}
在这里,线程 1 和线程 2 有可能导致死锁,因为线程 1 可能A
在线程 2 持有时正在持有B
,并且在另一个释放它的锁之前两者都不能继续。
If you must take multiple locks, always do it in the same order. If you're only taking one lock, then you won't cause a deadlock ... unless you hold a lock while waiting for user input, but that's not technically a deadlock and leads to another point: never hold a lock for any longer than you absolutely must.