I have a library that write in an array stored in shared memory. Now, I want to synchronize the process because there will be more process that can access and put element in this array. I'm studying semaphores but I don't understand why my process stuck without give me back any error. if I put a comment on the line of getSemaphoreWrite()
and releaseSemaphoreWrite()
the process works as well as without semaphore.
library:
void getSemaphoreWrite(){
int semID = semget(KEY_MB_WRITE, 0,0600);
struct sembuf sops;
sops.sem_num = 0;
sops.sem_op = -1;
semop(semID,&sops,1);
}
void releaseSemaphoreWrite(){
int semID = semget(KEY_MB_WRITE, 0,0600);
struct sembuf sops;
sops.sem_num = 0;
sops.sem_op = 1;
semop(semID,&sops,1);
}
int addBlock(struct Block block){
if(sizeMaster >= MAX_MASTER-1) return -1;
getSemaphoreWrite();
block.id = sizeMaster 1 ;
MasterBook[sizeMaster] = block;
sizeMaster;
printf("After add a block, size: %d",sizeMaster);
releaseSemaphoreWrite();
return 0;
}
struct :
struct Transaction {
int empty;
char timestamp[30];
int sender; /* pid user sent */
int receiver;
int reward;
int money;
};
struct Block
{
int id;
struct Transaction tr1;
struct Transaction tr2;
struct Transaction reward;
};
in master :
int semID = semget(KEY_MB_WRITE, 1, IPC_CREAT | 0600);
if(semID == -1){
perror("Error in sem: ");
exit(EXIT_FAILURE);
}
semctl(semID, 0, SETVAL, 0);
CodePudding user response:
This is expected.
The semctl(semID, 0, SETVAL, 0);
call initializes the semaphore with the value 0
. The first thing addBlock
attempts to do is do decrement it. The whole point of the semaphore is to block the process which would make its value negative.
Try to semctl(semID, 0, SETVAL, 1);
in master.