#include #include #include #include #include #include #include #include #define BUFF_SIZE 20 typedef struct { char buffer[BUFF_SIZE]; int nextIn; int nextOut; } shared_data; shared_data *shm, *s; char sem_name1[] = "mutex"; char sem_name2[] = "empty_slots"; char sem_name3[] = "full_slots"; sem_t *empty_slots; sem_t *full_slots; sem_t *mutex; void process(char item) { sem_wait(full_slots); sem_wait(mutex); item = s->buffer[s->nextOut]; tolower(item); s->nextOut = (s->nextOut + 1) % BUFF_SIZE; sem_post(mutex); printf("%u has changed Case of %c ...\n", pthread_self(), item); sem_post(full_slots); } void * Processor() { int i; char item; for(i = 0; i < 20; i++) { sleep(rand()%3); process(item); } } void main() { mutex=sem_open(sem_name1, O_CREAT,0644, 1); full_slots=sem_open(sem_name3, O_CREAT,0644, 0); empty_slots=sem_open(sem_name2, O_CREAT,0644, 10); //allocate the shared memory segment key_t key; key = 1234; //create the segment int shmid; if ((shmid = shmget(key, sizeof(shared_data), IPC_CREAT |0666)) <0) { perror("Shmget"); exit(1); } //attach to the segment if ((shm = (shared_data *) shmat(shmid, NULL, 0))==(shared_data *) -1) { perror("Shmat"); exit(1); } s=shm; s->nextIn = 0; //Producer( ); pthread_t pid[2]; pthread_create(&pid[0], NULL, Processor, NULL); pthread_create(&pid[1], NULL, Processor, NULL); pthread_create(&pid[2], NULL, Processor, NULL); pthread_join(pid, NULL); //detach shmdt((void *) shm); }