为什么对于setjmp / longjmp的volatile工作 [英] Why volatile works for setjmp/longjmp
问题描述
在调用longjmp()之后,如果自从调用setjmp()以来它们的值可能发生了更改,则不应访问非volatile限定的本地对象。他们在这种情况下的价值被认为是不确定的,访问它们是未定义的行为。
现在我的问题是为什么波动在这种情况下工作?在那个volatile变量中不会改变仍然会失败longjmp?例如,下面给出的示例中longjmp将如何正确工作?当代码返回到longjmp之后的setjmp时,local_var的值不是2而不是1?
void some_function )
{
volatile int local_var = 1;
setjmp(buf);
local_var = 2;
longjmp(buf,1);
setjmp
和 longjmp
clobber寄存器。如果一个变量存储在一个寄存器中,它的值会在 longjmp
之后丢失。相反,如果它被声明作为 volatile
,然后每次写入时都会将其存储回内存,并且每次读取时都会从内存中读回。这会损害性能,因为编译器必须执行更多的内存访问,而不是使用寄存器,但是它使得变量在
After invoking longjmp(), non-volatile-qualified local objects should not be accessed if their values could have changed since the invocation of setjmp(). Their value in this case is considered indeterminate, and accessing them is undefined behavior.
Now my question is why volatile works in this situation? Wouldn't change in that volatile variable still fail the longjmp? For example, how longjmp will work correctly in the example given below? When the code get backs to setjmp after longjmp, wouldn't the value of local_var be 2 instead of 1?
void some_function()
{
volatile int local_var = 1;
setjmp( buf );
local_var = 2;
longjmp( buf, 1 );
}
setjmp
and longjmp
clobber registers. If a variable is stored in a register, its value gets lost after a longjmp
.
Conversely, if it's declared as volatile
, then every time it gets written to, it gets stored back to memory, and every time it gets read from, it gets read back from memory every time. This hurts performance, because the compiler has to do more memory accesses instead of using a register, but it makes the variable's usage safe in the face of longjmp
ing.
这篇关于为什么对于setjmp / longjmp的volatile工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!