X
  • Work
    June 12, 2007

Volatile

Guest Author

The keyword volatile should be used in situations where an item of data is shared between multiple threads. An example of this is the code:

int ready;
...
while (ready);
...

This code gets compiled into:

/\* 0x0004            \*/         ld      [%o5+%lo(ready)],%o5
/\* 0x0008 \*/ cmp %o5,0
/\* 0x000c \*/ be,pn %icc,.L77000022
/\* 0x0010 \*/ nop
.L77000017:
/\* 0x0014 5 \*/ ba .L77000017
/\* 0x0018 \*/ nop
.L77000022:
/\* 0x001c 5 \*/ retl ! Result =
/\* 0x0020 \*/ nop

Compare this to the situation where the variable is declared as volatile:

                        .L900000106:
/\* 0x0018 5 \*/ cmp %o5,0
/\* 0x001c \*/ be,pn %icc,.L77000022
/\* 0x0020 \*/ nop
.L77000017:
/\* 0x0024 5 \*/ ld [%o2],%o3 ! volatile
/\* 0x0028 \*/ cmp %o3,0
/\* 0x002c \*/ bne,a,pt %icc,.L900000106
/\* 0x0030 \*/ ld [%o2],%o5 ! volatile
.L77000022:
/\* 0x0034 5 \*/ retl ! Result =
/\* 0x0038 \*/ nop

The endless loop has been removed, the variable is now polled.

The situation is interesting when using a pointer:

volatile int \* v1;
int \* volatile v2;
...
while (\*v1);
while (\*v2);
...

The two pointers are treated differently

                        .L900000109:
/\* 0x001c 6 \*/ cmp %o5,0
/\* 0x0020 \*/ be,pn %icc,.L900000110
/\* 0x0024 0 \*/ sethi %hi(v2),%g5
.L77000026:
/\* 0x0028 6 \*/ ld [%o4],%g1 ! volatile
/\* 0x002c \*/ cmp %g1,0
/\* 0x0030 \*/ bne,a,pt %icc,.L900000109
/\* 0x0034 \*/ ld [%o4],%o5 ! volatile
...
.L900000108:
/\* 0x0054 7 \*/ ld [%o5],%o4
/\* 0x0058 \*/ cmp %o4,0
/\* 0x005c \*/ be,pn %icc,.L77000039
/\* 0x0060 \*/ nop
.L77000034:
/\* 0x0064 7 \*/ ld [%g2],%o1 ! volatile
/\* 0x0068 \*/ ld [%o1],%o0
/\* 0x006c \*/ cmp %o0,0
/\* 0x0070 \*/ bne,a,pt %icc,.L900000108
/\* 0x0074 \*/ ld [%g2],%o5 ! volatile
...

v1 is a pointer to a volatile int, whereas v2 is a volatile pointer to an int. So v2 requires both the pointer and the data it points to to be reloaded, v1 only reloads the data being pointed to.

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.