My Photo

Shafqat's Recent Online Activity

« CLR Fun Stuff: How is my C# code converted into machine instructions? | Main | Back in Dhaka, New Job »

January 29, 2008

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00e54ee5d547883300e5501a46c48833

Listed below are links to weblogs that reference Multi-core CPU Caching: What is volatile?:

Comments

Moim Hossain

Again a good post.
I would like to add a bit more though. volatile variables are pretty useful while doing multi threading work, disregarding the number of CPU. While I used to write code in good-old C/C++ I came to know that, if there is a code snippet like..

int i = 0; // declare some where globally

//...then in some method

for( i = 0; i < 1024; ++ i)
{
// do something useful
}

Now assume some other method running concurrently that evaluates the value of i.

In this case, the compiler will optimize the variable i before starting the loop. it will initialize i with 0 before starting the loop and then load the value into the CPU register and will increment it directly into the register.
so the actual i in memory will hold zero for all the time the loop continues. Eventually when the loop terminates, the memory variable will be updated with the value 1024.
Therefore, if any other thread try to read the value of i during the looping, it will always find a zero and all of a sudden it will find a value 1024.
So if we need to get each iteration value for i in memory -from all thread, we need to declare the i as volatile.
if it is declared as volatile compiler will not optimize it during the loop incrementation.

I guess this was the primary theory inventing the key word volatile...(I am talking about the context of Turbo C, C++ while ppl were using 8086, and there was not even dreams of multiple CPU. )

Thanks shiplu bhai again for an informative post.

Moim Hossain

A quick experiment can be shown here..

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private int i = 0;

private void button1_Click(object sender, EventArgs e)
{
for (i = 0; i 0)
{
found = "YEAP";
}
}

private void button2_Click(object sender, EventArgs e)
{
this.Text = found;
}
}

In to the above code, if the i can be read something other than zero then the string found will hold a value YEAP. But it never happens. So alike C, C++ , C# is also not an exception.

Moim Hossain

:( some how the code snippet is getting screwed.

private int i = 0;

private void button1_Click(object sender, EventArgs e)
{
for (i = 0; i 0)
{
found = "YEAP";
}
}

private void button2_Click(object sender, EventArgs e)
{
this.Text = found;
}

Peter

But volatile variables are slower. It would have been great if there was a write volatile only variable.

look at ->

Thread.VolatileWrite

The comments to this entry are closed.

Feeds

Pages