From a3da640beebd64bef1f63b2f07f639dff3ff3c09 Mon Sep 17 00:00:00 2001 From: Tucker Evans Date: Sun, 26 Nov 2017 02:16:57 -0500 Subject: CS3871/assignments/sync: Added basic semaphore solution (no concurent readers) P(sem) crit V(sem) Removed debugging prints --- sync/writer.c | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) (limited to 'sync/writer.c') diff --git a/sync/writer.c b/sync/writer.c index b1ab9ed..d38dd70 100644 --- a/sync/writer.c +++ b/sync/writer.c @@ -4,12 +4,15 @@ #include #include #include +#include #include #include #include #include #include +#define NSEM 3 + char *mem; void quit(signum) @@ -23,9 +26,9 @@ int main(argc, argv) int argc; char **argv; { -printf("\tW STARTING\n"); - int shmid, i, pid, id; + int shmid, semid, i, pid, id; char *mem; + struct sembuf sb; if (argc < 2) { printf("usage: writer [id]\n"); @@ -34,7 +37,6 @@ printf("\tW STARTING\n"); id = atoi(argv[1]); -printf("\tW%d. started...\n", id); if ((shmid = shmget(52, 1<<14, IPC_CREAT | 0666)) == -1){ perror("shmget: shmget failed"); @@ -45,20 +47,30 @@ printf("\tW%d. started...\n", id); perror("shmat"); exit(1); } +printf("Wshmid: %x\n", shmid); + + if ((semid = semget(shmid, NSEM, 0)) == -1) { + perror("Wsemget: "); + exit(1); + } signal(SIGQUIT, quit); -printf("\tW%d. SHMID: %d\n", id, shmid); srand(time(NULL)); while (1) { -printf("\tW%d. testing...\n", id); rand() % id; -printf("\tW%d. writing...\n", id); + + sb.sem_num = 0; sb.sem_op = -1; sb.sem_flg = 0; + semop(semid, &sb, 1); + for (i = 0; i < 1<<14; i++) { mem[i]= 0x30 + id; } -printf("\tW%d. waiting...\n"); + + sb.sem_op = 1; + semop(semid, &sb, 1); + sleep(rand() % ((id * 2) + 1)); } } -- cgit v1.1