Commit a3c98986 authored by Son Pham's avatar Son Pham

Pre-lab 7 Completed

parent d203d3ed
CC = gcc
CFLAGS = -g
LFLAGS = -lpthread
ALL = dp
all : $(ALL)
dp: dp.c
$(CC) $(CFLAGS) $(LFLAGS) dp.c -o dp
clean:
/bin/rm -f *.o *~ core $(ALL)
\ No newline at end of file
/**
* Name: Son Pham
* Class: CSCI 315
* Prof: Luiz Felipe Perrone
* dp.c
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <pthread.h>
#define NUM_THREADS 5
#define SCALE_FACTOR 1000000
/**
* The philosopher thread
*/
void* philosopher(void* param) {
// Cast the param back to ID
int id = (intptr_t) param;
// Since ID is different across philosopher, use ID as seed
unsigned int seed = id;
// Temporary variable t
int t;
// Create a while loop that think, get hungry and eats
while(1) {
printf("Philosopher %d is thinking\n", id);
// sleep for random period of time
t = rand_r(&seed);
napping(t);
// Start eating
printf("Philosopher %d is hungry\n", id);
printf("Philosopher %d is ready to eat\n", id);
// Eat for some amount of time
t = rand_r(&seed);
napping(t);
// Done eating
printf("Philosopher %d is done eating\n", id);
}
}
/**
* Sleep for some amount of time
*/
int napping(int t) {
t = t / (RAND_MAX / SCALE_FACTOR);
usleep(t);
}
/**
* Main function
*/
int main() {
// Instantiate all philosopher threads
pthread_t tid[NUM_THREADS];
// Create 5 philosopher threads
int i;
for (i = 0; i < NUM_THREADS; i++) {
pthread_create(&tid[i], NULL, philosopher, (void*) (intptr_t) i);
}
// Sleep for then 10 seconds to make these threads run for a while
sleep(10);
// Return gracefully, will never get here tho
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment