英文:
Is Interlock.CompareExchange atomic inside an if statement?
问题
I am assuming that the piece of code is threadsafe,
if ((Interlocked.CompareExchange(ref semaphore, 1, 0) == 0))
{
//Do Stuff
semaphore = 0;
}
However I am wondering why:
In my mind I see this as two operations,
-
First it compares the semaphore with the value, and replaces it if they are equal
(Interlocked.CompareExchange(ref semaphore, 1, 0)
-
Then it compares the value it returns to 0, with the statement
{CompareExchange} == 0
Can not the semaphore be set somewhere else, before the second comparison (2.) happens? And that the function gets entered when it should not?
英文:
I am assuming that the piece of code is threadsafe,
if ((Interlocked.CompareExchange(ref semaphore, 1, 0) == 0))
{
//Do Stuff
semaphore = 0;
}
However I am wondering why:
In my mind I see this as two operations,
-
First it compares the semaphore with the value, and replaces it if they are equal
(Interlocked.CompareExchange(ref semaphore, 1, 0)
-
Then it compares the value it returns to 0, with the stamement
{CompareExchange} == 0
Can not the semaphore bet set somewhere else, before the second comparison (2.) happens? And that the function gets entered when it should not?
答案1
得分: 3
Interlocked.CompareExchange
是一个原子操作,会返回一个值。一旦发生这个操作,该方法调用的结果不会改变,除非再次调用 Interlocked.CompareExchange
,即使 semaphore
改变也不影响。这与它是否在 if
语句内无关;您可以依赖该返回值保持稳定。
英文:
Interlocked.CompareExchange
is an atomic operation, resulting in a return value. Once that happens, the result of that method call cannot change unless you call Interlocked.CompareExchange
again, even if semaphore
changes. It doesn't matter that it is inside an if
statement; you can depend on that return value to be stable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论