System V semaphore——demo

 

代码
   
     
#include sys / types.h >
#include sys
/ ipc.h >
#include sys
/ sem.h >
union semun{
int val;
struct semid_ds * buf;
unsigned
short * array;
struct seminfo * __buf;
};

// create the semaphore set,
// if key is IPC_PRIVATE, the semaphore is anonymous
int semaphore_create(key_t key, int number)
{
return semget(key, number, IPC_CREAT | IPC_EXCL | 0666 );
}

// set all semaphores to val
int semaphore_setAll( int semid, int number, int val)
{
int i;
union semun initVal;
unsigned
short valList[number];
for (i = 0 ; i < number; i ++ )
{
valList[i]
= val;
}
initVal.array
= & valList[ 0 ];
return semctl(semid, 0 , SETALL, initVal);
}

// get all semaphores to val
int semaphore_getAll( int semid, unsigned short ** val)
{
union semun ret;
ret.array
= * val;
return semctl(semid, 0 , GETALL, ret);
}

// set index-th semaphore to val
int semaphore_set( int semid, int index, int val)
{
union semun un;
un.val
= val;
return semctl(semid, index, SETVAL, un);
}

// get index-th semaphore to val
int semaphore_get( int semid, int index, int * val)
{
union semun un;
un.val
= * val;
return semctl(semid, index, GETVAL, un);
}

// delete the semaphore set
int semaphore_del( int semid)
{
return semctl(semid, 0 , IPC_RMID);
}

// v operation, here we just add one for example
int semaphore_v( int semid, int index)
{
// add the semaphore
struct sembuf operation;
operation.sem_num
= index;
operation.sem_op
= 1 ;
operation.sem_flg
= SEM_UNDO;
return semop(semid, & operation, 1 );
}

// p operation, here just del one for example
int semaphore_p( int semid, int index)
{
struct sembuf operation;
operation.sem_num
= index;
operation.sem_op
= - 1 ;
operation.sem_flg
= SEM_UNDO;
struct timespec delay;
delay.tv_sec
= 2 ;
delay.tv_nsec
= 0 ;
return semtimedop(semid, & operation, 1 , & delay);
}

 

 

你可能感兴趣的:(Semaphore)