62 lines
2.0 KiB
C++
62 lines
2.0 KiB
C++
#include <semaphore.h> // POSIX semaphores!
|
|
#include <pthread.h> // POSIX threads!
|
|
#include <unistd.h> // usleep
|
|
#include <stdio.h> // printf
|
|
#include "list.hpp" // list implementation
|
|
#include "globals.hpp" // globals/CPP defines
|
|
#include "producer.hpp" // Thread-1
|
|
#include "consumer.hpp" // Thread-3
|
|
#include "transformer.hpp" // Thread-2
|
|
|
|
// Create all of memory
|
|
block memory[N] = {0};
|
|
// create the three lists
|
|
list lists[3] = {0};
|
|
list *freelist = &lists[0], *list1 = &lists[1], *list2 = &lists[2];
|
|
|
|
// count semaphores
|
|
sem_t sem_freelist, sem_freelist_minus_1, sem_list1, sem_list2;
|
|
// binary semaphores
|
|
sem_t mut_freelist, mut_list1, mut_list2;
|
|
|
|
int main (int argc, char* argv[]) {
|
|
// initialize the freelist
|
|
list_init(freelist, memory, N);
|
|
|
|
//* Implement a semaphore solution to the problem
|
|
// counting semaphores measure the length
|
|
sem_init(&sem_freelist, 0, freelist->length);
|
|
sem_init(&sem_freelist_minus_1, 0, freelist->length-1);
|
|
sem_init(&sem_list1, 0, 0);
|
|
sem_init(&sem_list2, 0, 0);
|
|
// binary semaphores create mutual exclusion
|
|
sem_init(&mut_freelist, 0, 1);
|
|
sem_init(&mut_list1, 0, 1);
|
|
sem_init(&mut_list2, 0, 1);
|
|
|
|
//* Use pthreads to split execution
|
|
// Make some pthreads
|
|
pthread_t thread1, thread2, thread3;
|
|
// Create thread1 as producer
|
|
pthread_create(&thread1, NULL, producer, NULL);
|
|
// Create thread2 as transformer
|
|
pthread_create(&thread2, NULL, transformer, NULL);
|
|
// Create thread3 as consumer
|
|
pthread_create(&thread3, NULL, consumer, NULL);
|
|
// print some information about the 3 lists
|
|
while (true) {
|
|
printf("\033cfreelist: ");
|
|
list_print(freelist);
|
|
printf(" list1: ");
|
|
list_print(list1);
|
|
printf(" list2: ");
|
|
list_print(list2);
|
|
usleep(timescale);
|
|
}
|
|
// Wait for them to finish
|
|
pthread_join(thread1, NULL);
|
|
pthread_join(thread2, NULL);
|
|
pthread_join(thread3, NULL);
|
|
|
|
}
|