更改指针是否被视为 C 中的原子操作? [英] Is changing a pointer considered an atomic action in C?

查看:15
本文介绍了更改指针是否被视为 C 中的原子操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个通过引用读取缓存类型内存的多线程程序.我可以通过主线程更改此指针,而不会冒任何其他线程读取意外值的风险吗?

If I have a multi-threaded program that reads a cache-type memory by reference. Can I change this pointer by the main thread without risking any of the other threads reading unexpected values.

在我看来,如果更改是原子的,那么其他线程要么读取旧值,要么读取新值;永远不要随机内存(或空指针),对吧?

As I see it, if the change is atomic the other threads will either read the older value or the newer value; never random memory (or null pointers), right?

我知道无论如何我可能应该使用同步方法,但我仍然很好奇.

I am aware that I should probably use synchronisation methods anyway, but I'm still curious.

指针更改是原子的吗?

更新:我的平台是 64 位 Linux (2.6.29),虽然我也想要一个跨平台的答案:)

Update: My platform is 64-bit Linux (2.6.29), although I'd like a cross-platform answer as well :)

推荐答案

正如其他人所提到的,C 语言中没有任何东西可以保证这一点,它取决于你的平台.

As others have mentioned, there is nothing in the C language that guarantees this, and it is dependent on your platform.

在大多数现代桌面平台上,对字大小的对齐位置的读/写操作将是原子操作.但这并不能解决您的问题,因为处理器和编译器会重新排序读取和写入.

On most contemporary desktop platforms, the read/write to a word-sized, aligned location will be atomic. But that really doesn't solve your problem, due to processor and compiler re-ordering of reads and writes.

例如,下面的代码被破坏了:

For example, the following code is broken:

线程 A:

DoWork();
workDone = 1;

线程 B:

while(workDone != 0);

ReceiveResultsOfWork();

虽然对 workDone 的写入是原子的,但在许多系统上,处理器无法保证在通过DoWork() 是可见的.编译器也可以自由地将对 workDone 的写入重新排序到调用 DoWork() 之前.在这两种情况下,ReceiveResultsOfWork() 可能会开始处理不完整的数据.

Although the write to workDone is atomic, on many systems there is no guarantee by the processor that the write to workDone will be visible to other processors before writes done via DoWork() are visible. The compiler may also be free to re-order the write to workDone to before the call to DoWork(). In both cases, ReceiveResultsOfWork() might start working on incomplete data.

根据您的平台,您可能需要插入内存栅栏等以确保正确排序.这可能非常棘手.

Depending on your platform, you may need to insert memory fences and so on to ensure proper ordering. This can be very tricky to get right.

或者只是使用锁.简单得多,更容易验证是否正确,而且在大多数情况下,性能还不够.

Or just use locks. Much simpler, much easier to verify as correct, and in most cases more than performant enough.

这篇关于更改指针是否被视为 C 中的原子操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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