Operating System - HP-UX
1753765 Members
5771 Online
108799 Solutions
New Discussion юеВ

Re: Can we eliminate a memory barrier through code dependency ?

 
Lee gi choen
New Member

Can we eliminate a memory barrier through code dependency ?

We don't want to use a memory barrier and lock(such as spin lock, semaphore).
We hope to get the same effect like a memory barrier through artificial code dependency.
As far as I know.. if there is a "dependency" in C code , CPU or compiler doesn't reorder the instructions.
then.. I wrote berow code. can you 100% guarantee that it works?
any help will be appreciated.
thanks :)

[environment]
* HP-UX 11.31
* multi cpu, multi thread

---------------------------------------------------------
// The original code is simplified to be understood more easily.

struct data {
unsigned int x;
unsigned int sync_a;
unsigned int sync_b;
};

void setx(struct data * p, int t)
{
volatile unsigned int count = 0;
if ( count++ == 0) { p->sync_b++; }
p->x = t;
if (count++ != 0 ) { p->sync_a++; }
}


int getx(struct data * p)
{
unsigned int s0;
unsigned int s1;
unsigned int ret=0;
s0=0;
s1=0;
while(1)
{
volatile unsigned int count = 0;
if ( count++ == 0) { s0 = p->sync_a; }
ret = p->x;
if (count++ != 0 ) { s1 = p->sync_b; }
if( s0 == s1 )
{
break;
}
else
{
//pthread_yield();
}
}
return ret;
}

int main(void)
{
struct data pp = { 100,0,0 };
setx( &pp , 200 );
printf("%d\n", getx(&pp));
return 0;
}
---------------------------------------------------------
2 REPLIES 2
Dennis Handly
Acclaimed Contributor

Re: Can we eliminate a memory barrier through code dependency ?

You didn't mention whether PA or Integrity. I would forget about the former and use your mutexes.
Also you don't have any comments on what you are protecting, nor indicate where your multiple threads are and what you want to synchronize.

I'm not sure why you have these ifs:
if (count++ == 0) { p->sync_b++; }

Just remove them:
++count;
++p->sync_b;
ret = p->x;
++count;
++p->sync_a;

Or course this may not do what you want. Does this come from an algorithm on the web or book?
Laurent Menase
Honored Contributor

Re: Can we eliminate a memory barrier through code dependency ?

if I understand you you want to use our
if (count++..) as memory fencing

when you do your setx sync_a can not be flushed to central memory, while sync_b have been flushed by the if(count++!=0)

so you can have a discrepency between your sync_a and sync_b seen by an other cpu.

but you can be sure that p->x is flushed before sync_a

so indeed at a next loop you should get ret with the right value.