This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: volatile shared memory


On Fri, Mar 16, 2012 at 12:21 AM, Ian Lance Taylor <iant@google.com> wrote:
> NightStrike <nightstrike@gmail.com> writes:
>
>> If I am interacting with shared memory, gcc doesn't know if another
>> process changes values. ?This creates issues for optimization. ?I know
>> that "volatile" can help address this, but it winds up causing a giant
>> mess of other problems (like, for instance, I can't pass a volatile
>> into memcpy.. or pretty much anything else from the standard
>> libraries).
>
> No, volatile can not address this. ?This is not what the volatile
> qualifier is for. ?The volatile qualifier is designed for working with
> memory mapped hardware. ?It is not designed for multi-processor shared
> memory. ?If a program is not multi-processor safe, then adding volatile
> will never make it multi-processor safe.

Do you have to use volatile if you're writing to memory mapped
hardware, or just reading?

> This is because the issues related to making code multi-processor safe
> are related to memory barriers and memory cache behaviour. ?Adding a
> volatile qualifier will not change the program's behaviour with respect
> to either.

Is caching the reason that makes another process sharing a memory
address different than a piece of hardware sharing a memory address?

>> So for instance, if I do something stupidly simple like busy-wait on a
>> shm value to change:
>>
>> while (shm->index == oldindex) ;
>>
>> gcc will kill that loop.
>
> Just as well, since the program is most likely incorrect anyhow.
> Without any memory barrier, that expression could become true even
> though the executing processor can't see any of the other changes made
> to memory.
>
> Don't think volatile. ?Think memory barriers invoked via asm
> constructs. ?Use the new atomic builtins.

I thought (probably incorrectly) that the atomic builtins were only
for atomic actions between threads in a process, not between separate
processes.  Do they really work with the latter?  The information I
got on freenode's #gcc (not oftc) was that gcc can't do anything to
protect shared memory between processes, that you have to use a system
semaphore feature.

> And I can't help but add that most programs that work at this level get
> it wrong. ?Better to use mutexes and condition variables. ?Or even
> higher level constructs.
>
> Ian


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]