C Programming Tutorial

 
 
 
 
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/types.h>
#include<sys/shm.h>
#include \"headsem.h\"

int * bar_init(int np)
{
        int id,*bar;

        id=shmget(IPC_PRIVATE,10,0666|IPC_CREAT);
        bar=(int *)shmat(id,0,0);

        lock_init(&(bar[3]));

        bar[0]=np;
        bar[1]=0;
        bar[2]=0;
        bar[4]=id;

        return bar;
}

void barrier(int *bar)
{
        int flag=0;
        while(1)
        {
                locksem(&(bar[3]));
                if((flag==0) && (bar[2]>0))
                {
                        unlock(bar+3);
                        continue;
                }
                if(flag==0)
                {
                        bar[1]++;
                        flag=1;
                }
                if((bar[1]<bar[0]) && (bar[2]==0))
                {
                        unlock(bar+3);
                        continue;
                }
                        else
                {
                        if(bar[2]==0)
                        {
                                bar[1]=0;
                                bar[2]=bar[0]-1;
                                unlock(bar+3);
                                return;
                        }
                        else
                        {
                                bar[2]--;
                                unlock(bar+3);
                                return;
                        }
                }
                unlock(bar+3);
                exit(-1);
        }
}

/*void clean_bar(int *bar)
{
    free_sem(bar+3);
    free_shm(bar[4]);
}*/

 
 
Didn't find what you were looking for? Find more on PROGRAM OF CREATE HEADER FILE FOR BARRIER