473,804 Members | 3,178 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is *all* thread cached data flushed at MemoryBarrier

Obviously wrapping a critical section around access to some set of
shared state variables flushes any cached data, etc so that the threads
involved don't see a stale copy. What I was wondering is *what*
exactly gets flushed. Does the compiler some how determine the data
that is accessible from that thread, and flush just that set? (Seems
unlikely to me). Is it all data cached in registers etc? Or am I
overthinking this and instead it's more along the lines that a memory
barrier is just invalidating pages of memory such that when another
thread goes to access that memory it checks first to see if that page
needs to be refetched from main memory?

Thanks for any insights,
Tom

Aug 9 '06
20 1966
Brian Gideon <br*********@ya hoo.comwrote:
Maybe I'm wrong, but as I understand it the x86 memory model only
guarentees that writes cannot move with respect to other writes, but it
doesn't make any guarentees about reads. So it seems to me that you're
example is unsafe. But, I bet you'd have a hard time reproducing the
issue in reality. You'd almost certainly have to have a SMP system to
see it.
I thought that, but it's very easy to see "effective" memory read moves
- where a value is basically only read once instead of being reread
each time through a loop:

using System;
using System.Threadin g;

public class Test
{
static volatile bool stop;

static void Main()
{
ThreadStart job = new ThreadStart(Thr eadJob);
Thread thread = new Thread(job);
thread.Start();

// Let the thread start running
Thread.Sleep(50 0);

// Now tell it to stop counting
stop = true;

thread.Join();
}

static void ThreadJob()
{
int count=0;
while (!stop)
{
count++;

}
}
}

That stops half a second after you start it. Take the "volatile" bit
out, and it'll run forever (at least it does on my single processor P4,
when compiled with optimisation enabled).

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Aug 9 '06 #11
Jon Skeet [C# MVP] wrote:
Brian Gideon <br*********@ya hoo.comwrote:
>Maybe I'm wrong, but as I understand it the x86 memory model only
guarentees that writes cannot move with respect to other writes, but
it doesn't make any guarentees about reads. So it seems to me that
you're example is unsafe. But, I bet you'd have a hard time
reproducing the issue in reality. You'd almost certainly have to
have a SMP system to see it.

I thought that, but it's very easy to see "effective" memory read
moves
- where a value is basically only read once instead of being reread
each time through a loop:

using System;
using System.Threadin g;

public class Test
{
static volatile bool stop;

static void Main()
{
ThreadStart job = new ThreadStart(Thr eadJob);
Thread thread = new Thread(job);
thread.Start();

// Let the thread start running
Thread.Sleep(50 0);

// Now tell it to stop counting
stop = true;

thread.Join();
}

static void ThreadJob()
{
int count=0;
while (!stop)
{
count++;

}
}
}

That stops half a second after you start it. Take the "volatile" bit
out, and it'll run forever (at least it does on my single processor
P4, when compiled with optimisation enabled).
But this is just due to code hoisting by the JIT and has nothing to do with
the memory model at the CLR or CPU level. The volatile modifier inhibits
the hoising of the read out of the loop, so the thread stops like you'd
expect. Without voliatile, the read is hoisted and the variable only read
once, since the compiler can easily prove that nothing in the loop affects
the value of the variable.

-cd
Aug 10 '06 #12
Carl Daniel [VC++ MVP]
<cp************ *************** **@mvps.org.nos pamwrote:

<snip>
That stops half a second after you start it. Take the "volatile" bit
out, and it'll run forever (at least it does on my single processor
P4, when compiled with optimisation enabled).

But this is just due to code hoisting by the JIT and has nothing to do with
the memory model at the CLR or CPU level. The volatile modifier inhibits
the hoising of the read out of the loop, so the thread stops like you'd
expect. Without voliatile, the read is hoisted and the variable only read
once, since the compiler can easily prove that nothing in the loop affects
the value of the variable.
But it's the memory model which specifies what the JIT can do. That's
what I'm saying - regardless of CPU architecture, the JIT can do
optimisations which change the "apparent" read time of a variable. The
optimisations it's able to do are controlled by the memory model at the
CLR level.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Aug 10 '06 #13
First off, thanks to everyone contributing to the thread...this is why
I post here!

I have never used MemoryBarrior in any code other than tests for my own
education, as I said the original question was more theoritcal.

By the way, I have seen caching/reordering (it's often hard to
effectively tell which) in common environments.

This is kind of what I was investiagting. While I am well aware of
"how" to prevent it (and I of course do so), I wanted to know more
about what was going on under the covers.

And the fact that a simple question on the underlying behavior of a
memory barrier has blossomed into this debate on behavior only
underlines what I was saying before. There seems to be nothing
authoratative out there on this topic. If there us room for debate,
then there is room for error and misunderstandin g.

As an example of what I'd like see, I do a lot of p/invoke and COM
interop and the text ".NET and COM - The Complete Interoperabiliy
Guide" is my idea of a great book on that topic. I can only hope such
a volume is created in regards to concurency on the .NET / Windows
platform.

Thanks again,
Tom

Brian Gideon wrote:
Tom,

No, I do not believe it is safe. And even if it technically were I
certainly wouldn't bank on it because you may later port the code to
another framework version or hardware platform.

Maybe I'm wrong, but as I understand it the x86 memory model only
guarentees that writes cannot move with respect to other writes, but it
doesn't make any guarentees about reads. So it seems to me that you're
example is unsafe. But, I bet you'd have a hard time reproducing the
issue in reality. You'd almost certainly have to have a SMP system to
see it.

Here are some excellent links regarding memory barriers the .NET
framework.

<http://blogs.msdn.com/cbrumme/archive/2003/05/17/51445.aspx>
<http://discuss.develop .com/archives/wa.exe?A2=ind02 03B&L=DOTNET&P= R375>
<http://www.yoda.arachs ys.com/csharp/threads/volatility.shtm l>
<http://msdn.microsoft. com/msdnmag/issues/05/10/MemoryModels/>

Brian

NO***********@l ycos.com wrote:
OK.

So my example of watching a boolean is only unsafe on x86 if
instrucution (re)ordering is an issue, not because multiple threads
will see different values for that variable.

That's wasn't completely clear to me before.

Thanks!
Tom
Aug 10 '06 #14

Jon wrote:
That stops half a second after you start it. Take the "volatile" bit
out, and it'll run forever (at least it does on my single processor P4,
when compiled with optimisation enabled).

Which framework version were you using? I tried it with 1.1 and 2.0 on
my dual core laptop and I could only see it run forever with 2.0. I
guess 2.0 is more aggressive in its optimizations. At the very least
this proves that those who naively rely on it being safe in 1.1 will
get burned when they port their code to 2.0.

Aug 10 '06 #15
Brian Gideon wrote:
Jon wrote:
That stops half a second after you start it. Take the "volatile" bit
out, and it'll run forever (at least it does on my single processor P4,
when compiled with optimisation enabled).

Which framework version were you using? I tried it with 1.1 and 2.0 on
my dual core laptop and I could only see it run forever with 2.0. I
guess 2.0 is more aggressive in its optimizations. At the very least
this proves that those who naively rely on it being safe in 1.1 will
get burned when they port their code to 2.0.
I only tried it with 2.0 yesterday, but I think I've tried similar
programs with 1.1 before. I wouldn't like to swear to it though...

Jon

Aug 10 '06 #16
Tom,

One thing I should point out, which Jon already eluded to, is that we
code using the CLR memory model. The hardware memory model is mostly
irrelevant from a .NET developer's perspective because the CLR sits on
top of it. So your example is certainly unsafe because the CLR
specification says it is. We shouldn't be too concerned with the
differences between x86, AMD64, IA64, etc. architectures. That's the
job of the CLR. But, I do share your interest in learning exactly what
is going on behind the scenes.

Brian

NO***********@l ycos.com wrote:
OK.

So my example of watching a boolean is only unsafe on x86 if
instrucution (re)ordering is an issue, not because multiple threads
will see different values for that variable.

That's wasn't completely clear to me before.

Thanks!
Tom
Aug 10 '06 #17
This little sample shows reordering (or some type of caching) on 1.1:
class ConcurrencyTest
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{

ConcurrencyTest test = new ConcurrencyTest ();
test.Start();

}

private uint m_First;
private uint m_Second;
private System.Threadin g.Thread m_Incrementor;
private System.Threadin g.Thread m_Inspector;

public void Start()
{

Console.WriteLi ne("Tets running");

m_Incrementor = new Thread(new ThreadStart(Inc rement));
m_Inspector = new Thread(new ThreadStart(Che ckValues));
m_Incrementor.S tart();
m_Inspector.Sta rt();

}

private void Increment()
{
while(true)
{
m_First++;
m_Second++;
}
}

private void CheckValues()
{
while(true)
{

uint first = m_First ;
uint second = m_Second;

if (first < second)
{
Console.WriteLi ne("First is {0} and Second is {1}", first,second);
Thread.Sleep(10 00);
}

}

}
}


Jon Skeet [C# MVP] wrote:
Brian Gideon wrote:
Jon wrote:
That stops half a second after you start it. Take the "volatile" bit
out, and it'll run forever (at least it does on my single processor P4,
when compiled with optimisation enabled).
Which framework version were you using? I tried it with 1.1 and 2.0 on
my dual core laptop and I could only see it run forever with 2.0. I
guess 2.0 is more aggressive in its optimizations. At the very least
this proves that those who naively rely on it being safe in 1.1 will
get burned when they port their code to 2.0.

I only tried it with 2.0 yesterday, but I think I've tried similar
programs with 1.1 before. I wouldn't like to swear to it though...

Jon
Aug 10 '06 #18
NO***********@l ycos.com wrote:
This little sample shows reordering (or some type of caching) on 1.1:
I don't think so. It would be masked by the race condition between the
reads of m_First and m_Second. m_First could be read and m_Second
incremented several times before it is eventually read.

Aug 10 '06 #19
<NO***********@ lycos.comwrote:
This little sample shows reordering (or some type of caching) on 1.1:
I don't see anything - what do you see?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Aug 10 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
10625
by: DanGo | last post by:
Hi All, I'm trying to get my head around synchronization. Documentation seems to say that creating a volatile field gives a memorybarrier. Great! But when I do a little performance testing Thread.MemoryBarrier is 40 times slower than accessing a volatile int. Also I don't see any significant difference between the time to increment a volatile int and a
0
1522
by: Timo | last post by:
I'm trying to make a thread safe object cache without locking. The objects are cached by the id of the data dict given in __new__. Objects are removed from the cache as soon as they are no longer referenced. The type of the data must be a Python dict (comes from an external source). Here's what I've got so far: import time
5
9031
by: hugo27 | last post by:
hugo 27, Oct 9, 2004 Ref Docs: c.l.c FAQ article 12.26 . www.digitalmars.com sitemap.stdio.fflush Reading these Docs I understand that fflush does not summarily destroy or discard the flushed data. But it is not clear, in the case of fflush(stdin), where stdin is default C keyboard buffer, what actually becomes of the data.
14
1843
by: Michi Henning | last post by:
Hi, I can't find a statement about this in the threading sections in the doc... Consider: class Class1 { Class1() { _val = 42;
21
13110
by: JoKur | last post by:
Hello, First let me tell you that I'm very new to C# and learning as I go. I'm trying to write a client application to communicate with a server (that I didn't write). Each message from the server is on one line (\r\n at end) and is formed as - each of which is seperated by a space. Arguments with spaces in them are enclosed in quotations. So, I'm able to open a connection to the server. When I send a message to
5
4177
by: collection60 | last post by:
Hi people, I am writing a library that will implement a binary file format. Well... I'm thinking, as a design, it would be nice to have my library able to promise to not use more than a certain amount of RAM. I could have a "SetCacheSize(long NewSize);" function. So as part of that promise, when required memory exceeds that limit, the extra data is saved to disk and flushed from RAM.
1
1105
by: MindClass | last post by:
I've to modifying a file, then I use a method imported that access to that file and has to read the new data, but they are not read ( as if the data were not flushed at the moment even using .close() explicitly). --------------------------------------- ... ... # If it is not installed, it looking for the line and insert it. if not is_application:
2
2158
by: lwhitb1 | last post by:
Does anyone have any input on setting up my CAB application so that the application is thread safe, and cached appropiately? I read that this can be managed through Services, and dynamic injection. On the contrary, I was told that this can be handled using Enterprise Library cached application block. Last, but not least, i read you can implement this at the class level, creating immutable classes, and caching them accordingly. Any...
29
9152
by: NvrBst | last post by:
I've read a bit online seeing that two writes are not safe, which I understand, but would 1 thread push()'ing and 1 thread pop()'ing be thread-safe? Basically my situation is the follows: --Thread 1-- 1. Reads TCPIP Buffer 2. Adds Buffer to Queue (q.size() to check queue isn't full, and q.push_back(...)) 3. Signals Reading Thread Event & Goes Back to Wait for More Messages on TCPIP
0
9584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10583
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10323
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10082
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7622
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6854
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3822
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2995
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.