How To Add a Sequence Point?

David Brown david.brown@hesbynett.no
Sun Feb 3 21:11:00 GMT 2013


On 03/02/13 21:20, Jeffrey Walton wrote:
> On Sun, Feb 3, 2013 at 2:47 PM, David Brown <david.brown@hesbynett.no> wrote:
>> On 03/02/13 02:10, Jeffrey Walton wrote:
>>>
>>> So, it looks like I don't understand sequence points. Please forgive
>>> my ignorance.
>>>
>>> What does C/C++ and GCC offer to ensure writes are complete before
>>> reads are performed on a value in a multi-threaded program?
>>>
>> You are probably looking for a "memory barrier", rather than a "sequence
>> point".  But even that will not be enough if you have an SMP system - though
>> it might let you get better results from your Googling.  If possible, your
>> best bet is probably to use facilities provided by your OS - but that is
>> very much outside the scope of this mailing list.
>>
>> Anyway, the simplest memory barrier in gcc is :
>>
>>          asm volatile("" ::: "memory");
>>
>> This tells gcc that memory may be used in unexpected ways at this point in
>> the code - so any outstanding writes are handled before this point, and no
>> reads are started until after it.  But that only applies at the assembly
>> code level
> Thanks David. That's what I thought (memory barriers and ASM), but I
> did not want to taint other's answers, especially since it seemed like
> sequence points should have addressed my use cases.
>
>> the compiler does not control things like caches, write
>> buffers, read-ahead buffers, etc.
> So I am clear: caches, buffers etc are OS - and not CPU caches?

No, I am talking about CPU caches and buffers.  OS-related concepts of 
buffers and caches are controlled by OS system calls.

>
> Sorry to ask. I'm trying to figure out (or understand) where the
> disconnect occurs between the language and the implementation.
>

There are assembly-level instructions that can influence things like CPU 
caches (details vary according to processor), but "normal" C code cannot 
generate them.  A few C compilers on some targets will generate 
cache-control code, such as forcing a volatile write to skip the cache - 
but that is not common behaviour.  So to affect the cache, enforce 
memory access orders, etc., you need to either use assembly code, OS 
functions, additional compiler intrinsic functions or features, or 
additional library code.  The assembly memory barrier above will /not/ 
affect data caches or write buffers, and will therefore not affect 
memory ordering.  You have to use something like a cpu-specific 
instruction (such as asm volatile("msync" ::: "memory") on a PPC 
target), or atomic access using the gcc extensions or the newer C11 
atomic types, or an OS-specific feature.




More information about the Gcc mailing list