gpt4 book ai didi

c# - 互斥 : is this safe?

转载 作者:太空宇宙 更新时间:2023-11-03 17:08:46 27 4
gpt4 key购买 nike

这种互斥模式是否像我认为的那样安全?如果是这样,你怎么调用它?

lock (_lock) {
if (_flag) return;
else _flag = true;
}
try {
//critical code...
}
finally {
_flag = false;
}

我想确保临界区,但又不想让其他线程堆积起来等待获取锁。显然,我确保该标志没有设置在其他任何地方。有没有更好的办法?

最佳答案

不,那不安全。如果要保证互斥不阻塞,可以使用Monitor.TryEnter:

if (Monitor.TryEnter(lockObj, 0)) {
// got the lock !
try {
// code
}
finally { // release the lock
Monitor.Exit(lockObj);
}
}

关于c# - 互斥 : is this safe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/553480/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com