我如何在Windows上原子地交换两个指针? [英] How can I atomically swap two pointers on Windows?

查看:141
本文介绍了我如何在Windows上原子地交换两个指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我问的问题与这个删除的问题,但我要求它更直接。



我有两个指针变量在同一个类。我想交换这些变量的内容(不是它们的POINT,只是变量本身)。



我想避免锁



zillionInterlockedExchangePointer的答案,请先阅读 MSDN文档。 InterlockedExchangePointer将堆栈寄存器中的值与指针目标的值进行交换。它本身不会在内存位置交换两个指针。

解决方案

我要出去的肢体说你需要一个锁,并且没有一般情况下无锁的解决方案这个问题。



您需要从两个地址读取,并以原子方式回写到这两个地址。据我所知,X86只能原子地从单个存储器地址和寄存器交换数据。我不认为可以交换两个内存地址的内容。



如果你可以把约束放在指针的位置,你可以这样做。例如,如果可以保证指针在内存中相邻,则可以在循环中使用64位或128位比较/交换。



可能有解决方案对于其他简单的情况,但我不认为你会找到一个无锁解决方案的一般情况。


Okay, I'm asking the same thing as this deleted question, but I'm asking it more directly.

I've got two pointer variables in two instances of the same class. I'd like to swap the contents of those variables (not what they POINT to, just the variables themselves) atomically.

I'd like to avoid locks if at all possible.

How do I do this?

EDIT: To the three zillion "InterlockedExchangePointer" answers, please read the MSDN docs first. InterlockedExchangePointer exchanges the value of a pointer target with a value on the stack register. It (by itself) does not exchange two pointers in memory locations.

解决方案

I'm going to go out on a limb and say that you need a lock and that there is no general-case lock-free solution to this problem.

You would need to read from two addresses and write back to both addresses all atomically. To the best of my knowledge, X86 can only atomically exchange data from a single memory address and a register. I don't think it's possible to exchange the contents of two memory addresses.

If you can put constraints on where the pointers are, you can do this. For example, if you can guarantee the pointers are adjacent in memory, you can use a 64- or 128-bit compare/exchange in a loop.

There may be solutions for other simple cases, but I don't think you're going to find a lock-free solution for the general case.

这篇关于我如何在Windows上原子地交换两个指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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