SlideShare a Scribd company logo
1 of 5
Download to read offline
Please help me fix my code so the program executes per the instructions of this assignment. I
have written a C file for a roller coaster program using threads and semaphores. It must run in
Ubuntu. My program compiles, and the command line arguments work, but it will not execute
because of a segmentation fault. There are three functions, a main function, a passenger thread
function, and a car thread function. I believe the error to be in the function called car. Here is my
code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <stdbool.h>
sem_t rideEmpty, rideTurn, rideExit;
int passengerInPark = 0;
int passengerInSeat = 0;
int passengerIsDone = 0;
char i = 0, n = 0, c = 0;
//Passenger Thread Function
void *passenger(void *arg)
{
int id = *(int*) arg;
free(arg);
int j = 0;
int max_iter = rand() % i+1;
for (int j = 0; j < max_iter+1; j++)
{
int wait = rand() % 11;
sleep(wait);
sem_wait(&rideEmpty);
sem_wait(&rideTurn);
printf("033[0;32m Thread %d: Wooh! I'm about to ride the roller coaster for the %d th time! I have
%d iterations left. 033[0mn", id, j, max_iter - j);
passengerInSeat++;
sem_post(&rideTurn);
}
passengerIsDone++;
sem_wait(&rideExit);
printf("033[0;32m Thread %d: completed %d iterations on the roller coaster. Exiting. 033[0mn", id,
j);
passengerInPark--;
return NULL;
//pthread_exit(NULL);
}
//Car Thread Function
void *car(void *arg)
{
int rideCounter = 0;
while (passengerInPark > 0)
{
int time = 0;
while (time != 2 && passengerInSeat != c)
{
sleep(1);
time++;
}
sem_wait(&rideTurn);
printf("033[0;31 Car: %d passengers are riding the roller coaster. Off we go on the %d ride!
033[0mn", passengerInSeat, ++rideCounter);
sleep(5);
printf("033[0;31m Car: ride %d completed. 033[0mn", rideCounter);
int emptySeats = 0;
while(emptySeats < passengerInPark && emptySeats < c)
{
sem_post(&rideEmpty);
emptySeats++;
}
passengerInSeat = 0;
while (passengerIsDone > 0)
{
sem_post(&rideExit);
passengerIsDone = 0;
}
sem_post(&rideTurn);
}
printf("033[0;31m Car: Roller coaster shutting down.033[0mn");
return NULL;
//pthread_exit(NULL);
}
//Main Function
int main(int argc, char *argv[])
{
if (argc == 1)
{
printf("Usage: -n <count> -c <count> -i <count>nn");
return EXIT_SUCCESS;
}
char options;
while ((options = getopt(argc, argv, ":n:c:i:")) != -1)
{
switch (options)
{
case 'n':
n = atol(optarg);
if (n <= 0)
{
printf("./roller: invalid value - %snn", optarg);
return EXIT_SUCCESS;
}
break;
case 'c':
c = atoi(optarg);
if (c <= 0)
{
printf("./roller: invalid value - %snn", optarg);
return EXIT_SUCCESS;
}
break;
case 'i':
i = atoi(optarg);
if (i <= 0)
{
printf("./roller: invalid value - %snn", optarg);
return EXIT_SUCCESS;
}
break;
default:
printf("./roller: invalid option - %cnn", argv[optind-1][1]);
return EXIT_SUCCESS;
}
}
if ((c == 0) || (n == 0) || (i == 0)) return EXIT_SUCCESS;
if ((c >= n) || (n > 100))
{
printf("n (>c ) and n (<= 100) arguments requirednn");
return EXIT_SUCCESS;
}
//int passengerInSeat = atoi(argv[1]);
//rideNum = atoi(argv[2]);
n = atoi(argv[2]);
c = atoi(argv[4]);
i = atoi(argv[6]);
pthread_t passenger[passengerInSeat];
pthread_t car;
sem_init(&rideEmpty, 0, 0);
sem_init(&rideTurn, 0, 0);
sem_init(&rideExit, 0, 1);
for (int i = 0; i < passengerInSeat; i++)
{
int *id = malloc(sizeof(int));
*id = i;
pthread_create(&passenger[i], NULL, passenger, id);
}
pthread_create(&car, NULL, car, NULL);
for (int i = 0; i < passengerInSeat; i++)
{
pthread_join(passenger[i], NULL);
}
pthread_join(car, NULL);
sem_destroy(&rideEmpty);
sem_destroy(&rideTurn);
sem_destroy(&rideExit);
printf("main past semaphore destroysn");
return 0;
}
Here are the instructions:
Implement the Roller Coaster problem in C (not C++) ensuring the constraints are met and critical
sections are properly protected. The program must compile and execute under Ubuntu 22.04 LTS.
The Roller Coaster scenario is a concurrent programming problem that can be solved using
semaphores1 and is summarized below. This code requires multi-threading, semaphores, and
possibly overcoming deadlocks.
Suppose there are n passenger threads and one roller coaster car thread. The car can hold at
most c passengers, where c < n. Each passenger would ride the roller coaster for a random
number of times, and the random number is in the range [0, i]. After each ride, the passenger will
wait for a random time in the range [0s, 10s] to brace themselves. After completing their
predetermined number of iterations, the passenger will exit the park (i.e., the thread terminates).
Upon deciding to ride a roller coaster, the passenger must wait for an open seat to ride the roller
coaster car. The car waits for passengers for a maximum of 2s. Upon completing 2s or reaching
the maximum capacity, the car goes around the track for 5s. The roller coaster shuts down (the
car thread exits) after all passengers exit the park.
You will create one thread for each user and one thread for the car. The car thread will allow
passenger boarding for 2s or until the car is full. Once the boarding closes, the car goes on a ride
for 5s, represented by a sleep function call. The pseudo code for the car thread can be found
below:
Each user thread will wait for a random time in the rage [0, 10s] and then attempt to board the car.
During the boarding process, the user checks to see if the car is boarding passengers. If the car is
not boarding, the user thread will have to wait until the car is boarding. If the car is boarding
passengers, the user can check to see if a seat is available. If the seat is available, the user can
take the seat. However, if the seat is unavailable, the user will have to wait in the queue until the
car finishes a loop and there are empty seats. The Pseudo code for the passenger thread can be
found on the next page.
Pseudo code for the car and passenger:
The total number of passengers, n, the number of passengers per car, c, and the upper bound on
the maximum number of iterations of a passenger, i, will be accepted as command line arguments.
The accepted arguments should meet the following constraints: c < n, n < 100, and i <= 20. All
values must be > 0.
Include Files:
In order to use threading functions and semaphores in C, you will need the below include files:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <stdbool.h>
Compilation options: user the following compilation options:
gcc -Wall -g -pedantic -pthread -o roller roller.c
Example Output: the following are some execution examples showing error handling and an
example execution. Successive execution may vary. The $ is the prompt.
Correct output showing program execution:
The segmentation fault is preventing this program from executing properly with the thread print
outs above.
Car:Passenger: max i ter = random (0,i); while (j<=maxiter): wait(random (0,10s)); boardCar ();
print(" 033[0;32m Thread ID > : Wooh! I'm about to ride the roller coaster for the jth time! I have
max_iter j iterations left. 033[0mn);

More Related Content

Similar to Please help me fix my code so the program executes per the i.pdf

Project 3–Advanced Taxi SystemObjectiveTo gain experience and prac.pdf
Project 3–Advanced Taxi SystemObjectiveTo gain experience and prac.pdfProject 3–Advanced Taxi SystemObjectiveTo gain experience and prac.pdf
Project 3–Advanced Taxi SystemObjectiveTo gain experience and prac.pdf
aminbijal86
 
#include iostream#include string#include iomanip#inclu.docx
#include iostream#include string#include iomanip#inclu.docx#include iostream#include string#include iomanip#inclu.docx
#include iostream#include string#include iomanip#inclu.docx
mayank272369
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
eugeniadean34240
 
Assignment DIn Problem D1 we will use a file to contain the dat.pdf
Assignment DIn Problem D1 we will use a file to contain the dat.pdfAssignment DIn Problem D1 we will use a file to contain the dat.pdf
Assignment DIn Problem D1 we will use a file to contain the dat.pdf
fasttrackscardecors
 
1. BooleanSourceHW4 classpublic BooleanSourceHW4(double initProbab.pdf
1. BooleanSourceHW4 classpublic BooleanSourceHW4(double initProbab.pdf1. BooleanSourceHW4 classpublic BooleanSourceHW4(double initProbab.pdf
1. BooleanSourceHW4 classpublic BooleanSourceHW4(double initProbab.pdf
alimacal
 

Similar to Please help me fix my code so the program executes per the i.pdf (20)

Looping statements
Looping statementsLooping statements
Looping statements
 
Project 3–Advanced Taxi SystemObjectiveTo gain experience and prac.pdf
Project 3–Advanced Taxi SystemObjectiveTo gain experience and prac.pdfProject 3–Advanced Taxi SystemObjectiveTo gain experience and prac.pdf
Project 3–Advanced Taxi SystemObjectiveTo gain experience and prac.pdf
 
cbse 12 computer science investigatory project
cbse 12 computer science investigatory project  cbse 12 computer science investigatory project
cbse 12 computer science investigatory project
 
cbse 12 computer science investigatory project
cbse 12 computer science investigatory project  cbse 12 computer science investigatory project
cbse 12 computer science investigatory project
 
R, Scikit-Learn and Apache Spark ML - What difference does it make?
R, Scikit-Learn and Apache Spark ML - What difference does it make?R, Scikit-Learn and Apache Spark ML - What difference does it make?
R, Scikit-Learn and Apache Spark ML - What difference does it make?
 
Week9
Week9Week9
Week9
 
#include iostream#include string#include iomanip#inclu.docx
#include iostream#include string#include iomanip#inclu.docx#include iostream#include string#include iomanip#inclu.docx
#include iostream#include string#include iomanip#inclu.docx
 
Functions of stdio conio
Functions of stdio   conio Functions of stdio   conio
Functions of stdio conio
 
2 data and c
2 data and c2 data and c
2 data and c
 
(7) cpp abstractions inheritance_part_ii
(7) cpp abstractions inheritance_part_ii(7) cpp abstractions inheritance_part_ii
(7) cpp abstractions inheritance_part_ii
 
Sumo tutorial: 1) Manual Network creation, 2) OSM to Netwrok, 3) OD Matrix to...
Sumo tutorial: 1) Manual Network creation, 2) OSM to Netwrok, 3) OD Matrix to...Sumo tutorial: 1) Manual Network creation, 2) OSM to Netwrok, 3) OD Matrix to...
Sumo tutorial: 1) Manual Network creation, 2) OSM to Netwrok, 3) OD Matrix to...
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
 
12th CBSE Practical File
12th CBSE Practical File12th CBSE Practical File
12th CBSE Practical File
 
Assignment DIn Problem D1 we will use a file to contain the dat.pdf
Assignment DIn Problem D1 we will use a file to contain the dat.pdfAssignment DIn Problem D1 we will use a file to contain the dat.pdf
Assignment DIn Problem D1 we will use a file to contain the dat.pdf
 
1. BooleanSourceHW4 classpublic BooleanSourceHW4(double initProbab.pdf
1. BooleanSourceHW4 classpublic BooleanSourceHW4(double initProbab.pdf1. BooleanSourceHW4 classpublic BooleanSourceHW4(double initProbab.pdf
1. BooleanSourceHW4 classpublic BooleanSourceHW4(double initProbab.pdf
 
Railway reservation(c++ project)
Railway reservation(c++ project)Railway reservation(c++ project)
Railway reservation(c++ project)
 
Lab
LabLab
Lab
 
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...
 
Optimizing last mile delivery
Optimizing last mile deliveryOptimizing last mile delivery
Optimizing last mile delivery
 

More from ankit11134

Please modify the following code in C Here is the initial c.pdf
Please modify the following code in C Here is the initial c.pdfPlease modify the following code in C Here is the initial c.pdf
Please modify the following code in C Here is the initial c.pdf
ankit11134
 
please read below it will tell you what we are using L.pdf
please read below it will tell you what we are using   L.pdfplease read below it will tell you what we are using   L.pdf
please read below it will tell you what we are using L.pdf
ankit11134
 
Please read below instruction and please give me answer 1.pdf
Please read below instruction and please give me answer   1.pdfPlease read below instruction and please give me answer   1.pdf
Please read below instruction and please give me answer 1.pdf
ankit11134
 
Please only write java classes according to diagram below I.pdf
Please only write java classes according to diagram below I.pdfPlease only write java classes according to diagram below I.pdf
Please only write java classes according to diagram below I.pdf
ankit11134
 
Please modify the following code in C Make sure your code m.pdf
Please modify the following code in C Make sure your code m.pdfPlease modify the following code in C Make sure your code m.pdf
Please modify the following code in C Make sure your code m.pdf
ankit11134
 
please make feedbackcomment or response to this post Being.pdf
please make feedbackcomment or response to this post Being.pdfplease make feedbackcomment or response to this post Being.pdf
please make feedbackcomment or response to this post Being.pdf
ankit11134
 

More from ankit11134 (20)

Please modify the following code in C Here is the initial c.pdf
Please modify the following code in C Here is the initial c.pdfPlease modify the following code in C Here is the initial c.pdf
Please modify the following code in C Here is the initial c.pdf
 
please read below it will tell you what we are using L.pdf
please read below it will tell you what we are using   L.pdfplease read below it will tell you what we are using   L.pdf
please read below it will tell you what we are using L.pdf
 
Please read below instruction and please give me answer 1.pdf
Please read below instruction and please give me answer   1.pdfPlease read below instruction and please give me answer   1.pdf
Please read below instruction and please give me answer 1.pdf
 
Please read Sections 13 of the following paper Yufei Tao.pdf
Please read Sections 13 of the following paper  Yufei Tao.pdfPlease read Sections 13 of the following paper  Yufei Tao.pdf
Please read Sections 13 of the following paper Yufei Tao.pdf
 
Please provide all necessary steps b Let 2XEX+VarX.pdf
Please provide all necessary steps b Let 2XEX+VarX.pdfPlease provide all necessary steps b Let 2XEX+VarX.pdf
Please provide all necessary steps b Let 2XEX+VarX.pdf
 
Please provide a 150200 word response per question and incl.pdf
Please provide a 150200 word response per question and incl.pdfPlease provide a 150200 word response per question and incl.pdf
Please provide a 150200 word response per question and incl.pdf
 
Please only write java classes according to diagram below I.pdf
Please only write java classes according to diagram below I.pdfPlease only write java classes according to diagram below I.pdf
Please only write java classes according to diagram below I.pdf
 
Please mention Chicago style REFERENCES How Tourism Works A.pdf
Please mention Chicago style REFERENCES How Tourism Works A.pdfPlease mention Chicago style REFERENCES How Tourism Works A.pdf
Please mention Chicago style REFERENCES How Tourism Works A.pdf
 
Please present complete solution The data in the table below.pdf
Please present complete solution The data in the table below.pdfPlease present complete solution The data in the table below.pdf
Please present complete solution The data in the table below.pdf
 
Please pick a relevant company or make one up Consider the .pdf
Please pick a relevant company or make one up Consider the .pdfPlease pick a relevant company or make one up Consider the .pdf
Please pick a relevant company or make one up Consider the .pdf
 
Please help with the concept map for eukaryotic transcriptio.pdf
Please help with the concept map for eukaryotic transcriptio.pdfPlease help with the concept map for eukaryotic transcriptio.pdf
Please help with the concept map for eukaryotic transcriptio.pdf
 
Please modify the following code in C Make sure your code m.pdf
Please modify the following code in C Make sure your code m.pdfPlease modify the following code in C Make sure your code m.pdf
Please modify the following code in C Make sure your code m.pdf
 
Please match using only the given options Match the definiti.pdf
Please match using only the given options Match the definiti.pdfPlease match using only the given options Match the definiti.pdf
Please match using only the given options Match the definiti.pdf
 
Please match each component of the logic model presented her.pdf
Please match each component of the logic model presented her.pdfPlease match each component of the logic model presented her.pdf
Please match each component of the logic model presented her.pdf
 
please make feedbackcomment or response to this post Pro.pdf
please make feedbackcomment or response to this post   Pro.pdfplease make feedbackcomment or response to this post   Pro.pdf
please make feedbackcomment or response to this post Pro.pdf
 
please make feedbackcomment or response to this post Being.pdf
please make feedbackcomment or response to this post Being.pdfplease make feedbackcomment or response to this post Being.pdf
please make feedbackcomment or response to this post Being.pdf
 
Please make a lab report with the following Linux command li.pdf
Please make a lab report with the following Linux command li.pdfPlease make a lab report with the following Linux command li.pdf
Please make a lab report with the following Linux command li.pdf
 
Please label the image given characteristics Basement me.pdf
Please label the image given characteristics   Basement me.pdfPlease label the image given characteristics   Basement me.pdf
Please label the image given characteristics Basement me.pdf
 
Please include formulas This problem is based on a real acqu.pdf
Please include formulas This problem is based on a real acqu.pdfPlease include formulas This problem is based on a real acqu.pdf
Please include formulas This problem is based on a real acqu.pdf
 
Please help Two firms engage in simultaneousmove quantity .pdf
Please help Two firms engage in simultaneousmove quantity .pdfPlease help Two firms engage in simultaneousmove quantity .pdf
Please help Two firms engage in simultaneousmove quantity .pdf
 

Recently uploaded

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

Please help me fix my code so the program executes per the i.pdf

  • 1. Please help me fix my code so the program executes per the instructions of this assignment. I have written a C file for a roller coaster program using threads and semaphores. It must run in Ubuntu. My program compiles, and the command line arguments work, but it will not execute because of a segmentation fault. There are three functions, a main function, a passenger thread function, and a car thread function. I believe the error to be in the function called car. Here is my code: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <pthread.h> #include <semaphore.h> #include <time.h> #include <stdbool.h> sem_t rideEmpty, rideTurn, rideExit; int passengerInPark = 0; int passengerInSeat = 0; int passengerIsDone = 0; char i = 0, n = 0, c = 0; //Passenger Thread Function void *passenger(void *arg) { int id = *(int*) arg; free(arg); int j = 0; int max_iter = rand() % i+1; for (int j = 0; j < max_iter+1; j++) { int wait = rand() % 11; sleep(wait); sem_wait(&rideEmpty); sem_wait(&rideTurn); printf("033[0;32m Thread %d: Wooh! I'm about to ride the roller coaster for the %d th time! I have %d iterations left. 033[0mn", id, j, max_iter - j); passengerInSeat++; sem_post(&rideTurn); } passengerIsDone++; sem_wait(&rideExit); printf("033[0;32m Thread %d: completed %d iterations on the roller coaster. Exiting. 033[0mn", id, j); passengerInPark--;
  • 2. return NULL; //pthread_exit(NULL); } //Car Thread Function void *car(void *arg) { int rideCounter = 0; while (passengerInPark > 0) { int time = 0; while (time != 2 && passengerInSeat != c) { sleep(1); time++; } sem_wait(&rideTurn); printf("033[0;31 Car: %d passengers are riding the roller coaster. Off we go on the %d ride! 033[0mn", passengerInSeat, ++rideCounter); sleep(5); printf("033[0;31m Car: ride %d completed. 033[0mn", rideCounter); int emptySeats = 0; while(emptySeats < passengerInPark && emptySeats < c) { sem_post(&rideEmpty); emptySeats++; } passengerInSeat = 0; while (passengerIsDone > 0) { sem_post(&rideExit); passengerIsDone = 0; } sem_post(&rideTurn); } printf("033[0;31m Car: Roller coaster shutting down.033[0mn"); return NULL; //pthread_exit(NULL); } //Main Function int main(int argc, char *argv[]) { if (argc == 1)
  • 3. { printf("Usage: -n <count> -c <count> -i <count>nn"); return EXIT_SUCCESS; } char options; while ((options = getopt(argc, argv, ":n:c:i:")) != -1) { switch (options) { case 'n': n = atol(optarg); if (n <= 0) { printf("./roller: invalid value - %snn", optarg); return EXIT_SUCCESS; } break; case 'c': c = atoi(optarg); if (c <= 0) { printf("./roller: invalid value - %snn", optarg); return EXIT_SUCCESS; } break; case 'i': i = atoi(optarg); if (i <= 0) { printf("./roller: invalid value - %snn", optarg); return EXIT_SUCCESS; } break; default: printf("./roller: invalid option - %cnn", argv[optind-1][1]); return EXIT_SUCCESS; } } if ((c == 0) || (n == 0) || (i == 0)) return EXIT_SUCCESS; if ((c >= n) || (n > 100)) { printf("n (>c ) and n (<= 100) arguments requirednn");
  • 4. return EXIT_SUCCESS; } //int passengerInSeat = atoi(argv[1]); //rideNum = atoi(argv[2]); n = atoi(argv[2]); c = atoi(argv[4]); i = atoi(argv[6]); pthread_t passenger[passengerInSeat]; pthread_t car; sem_init(&rideEmpty, 0, 0); sem_init(&rideTurn, 0, 0); sem_init(&rideExit, 0, 1); for (int i = 0; i < passengerInSeat; i++) { int *id = malloc(sizeof(int)); *id = i; pthread_create(&passenger[i], NULL, passenger, id); } pthread_create(&car, NULL, car, NULL); for (int i = 0; i < passengerInSeat; i++) { pthread_join(passenger[i], NULL); } pthread_join(car, NULL); sem_destroy(&rideEmpty); sem_destroy(&rideTurn); sem_destroy(&rideExit); printf("main past semaphore destroysn"); return 0; } Here are the instructions: Implement the Roller Coaster problem in C (not C++) ensuring the constraints are met and critical sections are properly protected. The program must compile and execute under Ubuntu 22.04 LTS. The Roller Coaster scenario is a concurrent programming problem that can be solved using semaphores1 and is summarized below. This code requires multi-threading, semaphores, and possibly overcoming deadlocks. Suppose there are n passenger threads and one roller coaster car thread. The car can hold at most c passengers, where c < n. Each passenger would ride the roller coaster for a random number of times, and the random number is in the range [0, i]. After each ride, the passenger will wait for a random time in the range [0s, 10s] to brace themselves. After completing their predetermined number of iterations, the passenger will exit the park (i.e., the thread terminates). Upon deciding to ride a roller coaster, the passenger must wait for an open seat to ride the roller
  • 5. coaster car. The car waits for passengers for a maximum of 2s. Upon completing 2s or reaching the maximum capacity, the car goes around the track for 5s. The roller coaster shuts down (the car thread exits) after all passengers exit the park. You will create one thread for each user and one thread for the car. The car thread will allow passenger boarding for 2s or until the car is full. Once the boarding closes, the car goes on a ride for 5s, represented by a sleep function call. The pseudo code for the car thread can be found below: Each user thread will wait for a random time in the rage [0, 10s] and then attempt to board the car. During the boarding process, the user checks to see if the car is boarding passengers. If the car is not boarding, the user thread will have to wait until the car is boarding. If the car is boarding passengers, the user can check to see if a seat is available. If the seat is available, the user can take the seat. However, if the seat is unavailable, the user will have to wait in the queue until the car finishes a loop and there are empty seats. The Pseudo code for the passenger thread can be found on the next page. Pseudo code for the car and passenger: The total number of passengers, n, the number of passengers per car, c, and the upper bound on the maximum number of iterations of a passenger, i, will be accepted as command line arguments. The accepted arguments should meet the following constraints: c < n, n < 100, and i <= 20. All values must be > 0. Include Files: In order to use threading functions and semaphores in C, you will need the below include files: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <pthread.h> #include <semaphore.h> #include <time.h> #include <stdbool.h> Compilation options: user the following compilation options: gcc -Wall -g -pedantic -pthread -o roller roller.c Example Output: the following are some execution examples showing error handling and an example execution. Successive execution may vary. The $ is the prompt. Correct output showing program execution: The segmentation fault is preventing this program from executing properly with the thread print outs above. Car:Passenger: max i ter = random (0,i); while (j<=maxiter): wait(random (0,10s)); boardCar (); print(" 033[0;32m Thread ID > : Wooh! I'm about to ride the roller coaster for the jth time! I have max_iter j iterations left. 033[0mn);