错误地使用 InterlockedCompareExchange 以原子方式复制值? [英] Incorrect use of InterlockedCompareExchange to copy a value atomically?

查看:54
本文介绍了错误地使用 InterlockedCompareExchange 以原子方式复制值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能在这里使用 C++11 原子

我对使用 InterlockedCompareExchange() 来原子地"读取变量有疑问.

I have a doubt about my use of InterlockedCompareExchange() in order to 'atomically' read a variable.

我在这里问了一个问题,但我在那里做的事情不一样.交换"和操作数"参数(第 2 个和第 3 个)是硬编码"值,即不是从变量中读取的.

I asked a question about this here, but what I was doing there was different. The "exchange" and "comperand" parameters (2nd and 3rd) were 'hard coded' values, i.e. not read from a variable.

请考虑:

    // Copy the connect time
    DWORD dwConnectTime = InterlockedCompareExchange(&msgInfo.m_dwConnectTime, 
                            msgInfo.m_dwConnectTime, 
                            msgInfo.m_dwConnectTime);

这旨在将 msgInfo.m_dwConnectTime 的值与 msgInfo.m_dwConnectTime 的当前值交换,前提是 msgInfo.m_dwConnectTime 的当前值code> 是 msgInfo.m_dwConnectTime.然后返回 msgInfo.m_dwConnectTime 的先前值,这是我用来复制"值的.

This is intended to swap the value of msgInfo.m_dwConnectTime with the current value of msgInfo.m_dwConnectTime, provided the current value of msgInfo.m_dwConnectTime is msgInfo.m_dwConnectTime. The previous value of msgInfo.m_dwConnectTime is then returned, which is what I rely on to 'copy' the value.

虽然我刚刚意识到对第二个和第三个参数本身的 msgInfo.m_dwConnectTime 读取不能保证是原子的.因此,此代码是否不正确,因此我需要使用锁定原语来复制 msgInfo.m_dwConnectTime?

It has just dawned on me though that the reads of msgInfo.m_dwConnectTime for the second and third parameters themselves are not guaranteed to be atomic. Thus, is this code incorrect hence I need to use a locking primitive to copy msgInfo.m_dwConnectTime?

推荐答案

根据评论以及指向您之前问题的链接,提出这个问题的原因是您希望避免撕裂.读取和写入对齐的数据是原子的.您正在尝试防止撕裂,但在对齐数据时无法进行撕裂.并且可以合理地假设您的数据是对齐的,因为这是 InterlockedCompareExchange 和所有 InterlockedXXX 函数的要求.

Based on the comments, and the link to your earlier question, this question is motivated by your desire to avoid tearing. Reading from and writing to aligned data is atomic. You are attempting to guard against tearing, but tearing is not possible when the data is aligned. And it is reasonable to assume that your data is aligned because that is a requirement of InterlockedCompareExchange and indeed all the InterlockedXXX functions.

因此,您提出的问题不合逻辑.这是基于错误的前提,即对齐的数据可能会发生撕裂.

As such, the question you are asking is something of a non sequitur. It is based on the false premise that tearing can happen with aligned data.

因此,您不需要调用 InterlockedCompareExchange 或任何其他 InterlockedXXX 函数来避免撕裂,因为只有在数据未对齐时才能进行撕裂.

So, you don't need to call InterlockedCompareExchange or any other InterlockedXXX function in order to avoid tearing, because tearing is only possible when the data is not aligned.

这篇关于错误地使用 InterlockedCompareExchange 以原子方式复制值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆