编译器在多线程程序中对寄存器的使用 [英] Usage of registers by the compiler in multithreaded program

查看:238
本文介绍了编译器在多线程程序中对寄存器的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个普遍的问题,但是:

It is a general question but:

在多线程程序中,编译器使用寄存器临时存储全局变量是否安全?

In a multithreaded program, is it safe for the compiler to use registers to temporarily store global variables?

我认为不是,因为将全局变量存储在寄存器中可能会更改保存的值 用于其他线程.

I think its not, since storing global variables in registers may change saved values for other threads.

如何使用寄存器存储在函数中定义的局部变量?

And how about using registers to store local variables defined within a function?

我认为还可以,因为没有其他线程能够获取这些变量.

I think it is ok,since no other thread will be able to get these variables.

如果我错了,请纠正我. 谢谢!

Please correct me if im wrong. Thank you!

推荐答案

事情比您想象的要复杂得多.

Things are much more complicated than you think they are.

即使编译器将值存储到内存中,CPU通常也不会立即将数据推出RAM.它将其存储在缓存中(某些系统在处理器和内存之间具有2或3级缓存).

Even if the compiler stores a value to memory, the CPU generally does not immediately push the data out to RAM. It stores it in a cache (and some systems have 2 or 3 levels of caches between the processor and the memory).

更糟糕的是,编译器决定的指令顺序可能并不是实际执行的顺序,因为许多处理器可以在自己的管道中对指令(甚至指令的子部分)进行重新排序.

To make things worse, the order of instructions that the compiler decides, may not be what actually gets executed as many processors can reorder instructions (and even sub-parts of instructions) in their own pipelines.

通常,在多线程环境中,除非以下情况之一为真,否则您应该亲自避免从两个单独的线程访问(读取或写入)相同的内存:

In general, in a multithreaded environment you should personally take care to never access (either read or write) the same memory from two separate threads unless one of the following is true:

  • 您正在使用几种特殊的原子操作之一,以确保正确的同步.
  • 您已使用几种同步操作之一来保留"对共享数据的访问权,然后放弃"它.这些确实包括必需的内存屏障,这些屏障也保证了数据应该是预期的.

您可能需要阅读 http://en.wikipedia.org/wiki/Memory_ordering#Memory_barrier_types http://en.wikipedia.org/wiki/Memory_barrier

如果您准备好头疼一些,并且想知道事情可能会变得多么复杂,这是您的晚间讲座

If you are ready for a little headache and want to see how complicated things can actually get, here is your evening lecture Memory Barriers: a Hardware View for Software Hackers.

这篇关于编译器在多线程程序中对寄存器的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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