Java的挥发性用C? [英] Java's volatile in C?

查看:136
本文介绍了Java的挥发性用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Java中使用挥发性的。
即(基于维基百科的文章):

I'm aware of the use of volatile in Java. That is (based on the wikipedia article):

有一个全球性排序的读取和写入挥发性
  变量。这意味着,每个线程访问一个volatile字段
  将继续之前读取其电流值,而不是
  使用缓存值(可能)。

There is a global ordering on the reads and writes to a volatile variable. This implies that every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value.

我也我知道,存在于C,但在一个完全不同的上下文中的挥发性关键字,主要是在内存映射I / O使用。

I also I'm aware that there exists the volatile keyword in C but in a quite different context, mainly to be used in memory-mapped I/O.

所以我想知道,有没有像Java的挥发性一些C结构?这将prevent
读一个变量的缓存值?

So I was wondering, is there some construct like Java's volatile in C? Which will prevent reading cached values of a variable?

如果它不存在C,有也许这样的结构,如的pthread

If it doesn't exist in C, is there perhaps a library with such a construct, like pthread?

推荐答案

挥发性在C是基本上被用于一个完全不同的场景,是没有用的不合时宜多线程编程。由于某些原因或其他即使是最新的C ++标准不能给它更多的意义,但必须发明新的关键字。

volatile in C is basically an anachronism that was intended for a completely different scenario and is NOT useful for multi threaded programming. For some reasons or another even the newest c++ standard couldn't give it more meaning but had to invent a new keyword instead.

你要知道这个手段挥发性 C标准的定义也没用,编译器可能会给你额外的保障(我知道,MS VC做,我认为它给基本同样的保障,确实在Java挥发性的),但是这意味着程序被锁定到一个编译器。大多数编译器也有一些内在函数插入内存屏障,这是更明确了一点,但不再便携式本身。

Mind you this means volatile as defined by the C standard is useless, compilers may give you additional guarantees (I know that MS VC does and I think it gives basically the same guarantees as does volatile in java) but that means the program is locked to that one compiler. Most compilers also have some intrinsics to insert memory barriers, which is a bit more explicit but again not portable per se.

在实践中你可能最好使用一些更高级别的线程库,它提供了合适的工具工作。例如。 POSIX给你低级别的内存壁垒AFAIK。

In practice you're probably best of using some higher level threading library that offers the right tools for the job. E.g. POSIX gives you low level memory barriers afaik.

在C ++的网站这是自为0x11好 - 标准确实提供了的std :: atomic_thread_fence 和原子变量。不过,请注意C ++的内存为0x11模式是不会等同于Java的人,所以你必须移植时要小心。

On the c++ site it's better since 0x11 - the standard does offer std::atomic_thread_fence and atomic variables. Note though that the c++0x11 memory model is NOT identical to the java one, so you'll have to be careful when porting.

这篇关于Java的挥发性用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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