Unix Programming - shared memory between processes

This is Interesting: Free IT Magazines  
Home > Archive > Unix Programming > May 2005 > shared memory between processes





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author shared memory between processes
Chris Friesen

2005-05-03, 6:00 pm

When sharing memory between processes, is the use of locking primitives
(fcntl, flock, sysV semas, NPTL process-shared operations, etc.)
sufficient to ensure that gcc will not optimize away the load from the
shared memory area?

Or do I need to also make it volatile?

As an example, consider the following code, where the locking operations
could be any one of the ones listed above:


int *b;

int test()
{
b=<address of shared memory>;

while(1) {
<lock>
if (*b) {
break;
}
<unlock>
}
<unlock>

return *b;
}

Without the locks, the compiler is free to only load *b once (and in
fact gcc does so). Is the addition of the locks sufficient to force *b
to be re-read each time, or do I need to declare it as

volatile int *b;


Thanks,

Chris
David Schwartz

2005-05-03, 6:00 pm


"Chris Friesen" <cfriesen@nortelnetworks.com> wrote in message
news:d58r0m$i3r$1@zcars129.ca.nortel.com...

> When sharing memory between processes, is the use of locking primitives
> (fcntl, flock, sysV semas, NPTL process-shared operations, etc.)
> sufficient to ensure that gcc will not optimize away the load from the
> shared memory area?


Yes. Any mechanism another thread could use to access the memory could
also be used by the locking primitives, as far as GCC knows, so it must
reload.

DS


Chris Friesen

2005-05-03, 6:00 pm

David Schwartz wrote:

> Yes. Any mechanism another thread could use to access the memory could
> also be used by the locking primitives, as far as GCC knows, so it must
> reload.


Okay, that makes sense for the pthread ones. I wasn't sure that the
same would hold true for the strictly process-based ones (fcntl/flock/etc.).

Chris
David Schwartz

2005-05-03, 6:00 pm


"Chris Friesen" <cfriesen@nortelnetworks.com> wrote in message
news:d58s0a$ks8$1@zcars129.ca.nortel.com...

> David Schwartz wrote:


[vbcol=seagreen]
> Okay, that makes sense for the pthread ones. I wasn't sure that the same
> would hold true for the strictly process-based ones (fcntl/flock/etc.).


Any mechanism another process could use could also be used by another
thread or by the lock/unlock functions. That's how it magically happens to
work. (Of course, if it didn't magically happen to work, it would be made to
work by some other mechanism. But that's not needed. The synchronization
functions work.)

DS


Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com