CoE165 2024 Assignment 06
Revision as of 23:02, 9 December 2024 by Louis Alarcon (talk | contribs) (Created page with "== CoE165 Assignment 5 == === Part 1: POSIX Thread Programming === A simple parking lot controller keeps track of the number of used slots, and continuously receives car sens...")
CoE165 Assignment 5
Part 1: POSIX Thread Programming
A simple parking lot controller keeps track of the number of used slots, and continuously receives car sensor data from entrances and exits, and the total number of parking slots is . The code below creates a separate thread for each sensor, and simulates the arrival and departure of cars by generating a random number for each sensor every second.
- Try it out!
- Try changing the initial number of used slots, the number of entrances and exits, and the length of the simulation (now at 100 seconds). Is the program behaving as you expected?
- What is a mutex used for?
- A good reference for beginners:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
// Parking controller with N entrances and M exits.
// Each entrance/exit has a car sensor.
// The controller keeps track of all the cars in the parking lot via the variable CarCount.
// Each entrace generates a random number every second as its input (0 or 1).
// Assume that the parkig lot has P total parking slots.
#define N 3
#define M 5
#define P 500
// What is a 'mutex'?
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int used_slots = 200;
void* function_entrance(void* arg)
{
int x, z;
srand(time(NULL));
for (z = 0; z <= 100; z++)
{
x = rand();
if (x > RAND_MAX / 2)
{
pthread_mutex_lock( &mutex1 );
if (used_slots < P)
used_slots++;
else
used_slots = P;
printf("Counter value: %d (entrance) - Thread: %ld\n",used_slots, pthread_self());
pthread_mutex_unlock( &mutex1 );
}
fflush(stdout);
sleep(1);
}
}
void* function_exit(void* arg)
{
int x, z;
srand(time(NULL));
for (z = 0; z <= 100; z++)
{
x = rand();
if (x > RAND_MAX / 2)
{
pthread_mutex_lock( &mutex1 );
if (used_slots > 0)
used_slots--;
else
used_slots = 0;
printf("Counter value: %d (exit) - Thread: %ld\n", used_slots, pthread_self());
pthread_mutex_unlock( &mutex1 );
}
fflush(stdout);
sleep(1);
}
}
int main(void)
{
pthread_t threadID1[N], threadID2[M];
void* exitStatus;
int a, b, c, d, e;
int value = 1;
for(a=0; a<N; a++)
pthread_create(&threadID1[a], NULL, function_entrance, &value);
for(b=0; b<M; b++)
pthread_create(&threadID2[b], NULL, function_exit, &value);
for(e=0; e<=100; e++)
{
printf("--> Main program sees counter value as: %d\n", used_slots);
fflush(stdout);
sleep(1);
}
for(c=0; c<N; c++)
{
pthread_join(threadID1[c], &exitStatus);
printf("Entrance thread %d completed.\n", c+1);
}
for(d=0; d<M; d++)
{
pthread_join(threadID2[d], &exitStatus);
printf("Exit thread %d completed.\n", d+1);
}
printf("--> Main program sees the FINAL counter value as: %d\n", used_slots);
printf("Done.\n");
return 0;
}