正在改变视为C中的原子操作的指针? [英] Is changing a pointer considered an atomic action in C?

查看:249
本文介绍了正在改变视为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.

例如,下面的code被打破:

For example, the following code is broken:

主题答:

DoWork();
workDone = 1;

线程B:

while(workDone != 0);

ReceiveResultsOfWork();

虽然写 workDone 是原子,在许多系统没有保证的处理器,在写 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天全站免登陆