You are on page 1of 3

ATOMIC COUNTER UPDATE PROBLEM Aim To implement atomic counter update problem Algorithm 1. 2. 3. 4.

Start the program Initialize semaphore Get data Implement thefollowing process boolean test_and_set(boolean* lock) atomic { boolean initial = *lock; *lock = true; return initial; } 5. atomic = executed without interruption 6. stop the program

#include<stdio.h> #include<unistd.h> #include<sys/shm.h> #include<sys/sem.h> #include<sys/ipc.h> #include<sys/types.h> #define key 204 main() { int balance = 500; static struct sembuf unlock[1] = {0,-1,IPC_NOWAIT}; static struct sembuf lock[2] = {0,0,0,0,1,0}; int semid = semget(key,1,IPC_CREAT|0666); int shmid,pid,deposit,withdraw ;

void *shmptr; struct shmid_ds myshmid_ds; shmid = shmget(IPC_PRIVATE,1,0666|IPC_CREAT); if(semid<1) { printf(" Semaphore not created "); } pid = fork(); if(pid != 0) { shmptr = shmat(shmid,0,SHM_R); sleep(5); semop(semid,&lock[0],2); balance = *(int *)shmptr; printf("\n Enter the With Draw Ammount : Rs. "); scanf("%d",&withdraw); balance = balance-withdraw; printf("\n Balance After the With Draw Ammount : Rs. %d",balance); semop(semid,&unlock[0],1); } else { shmptr = shmat(shmid,0,SHM_W); semop(semid,&lock[0],2); printf("\n Enter the Deposit Ammount : Rs. ");

scanf("%d",&deposit); balance = balance + deposit; *(int *)shmptr = balance; printf("\n Balance After Deposit : Rs. %d \n",balance); semop(semid,&unlock[0],1); } shmctl(shmid,IPC_RMID,&myshmid_ds); semctl(semid,0,IPC_RMID,0); } Output : Enter the Deposit Ammount : Rs. 1000 Balance After Deposit : Rs. 1500 Enter the With Draw Ammount : Rs. 500 Balance After the With Draw Ammount : Rs. 1000

You might also like