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.pdfaminbijal86
 
cbse 12 computer science investigatory project
cbse 12 computer science investigatory project  cbse 12 computer science investigatory project
cbse 12 computer science investigatory project D. j Vicky
 
cbse 12 computer science investigatory project
cbse 12 computer science investigatory project  cbse 12 computer science investigatory project
cbse 12 computer science investigatory project D. j Vicky
 
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?Villu Ruusmann
 
#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.docxmayank272369
 
Functions of stdio conio
Functions of stdio   conio Functions of stdio   conio
Functions of stdio conio Bhavik Vashi
 
(7) cpp abstractions inheritance_part_ii
(7) cpp abstractions inheritance_part_ii(7) cpp abstractions inheritance_part_ii
(7) cpp abstractions inheritance_part_iiNico Ludwig
 
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...Rodrigue Tchamna
 
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 - JavaTpointJavaTpoint.Com
 
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.docxeugeniadean34240
 
12th CBSE Practical File
12th CBSE Practical File12th CBSE Practical File
12th CBSE Practical FileAshwin Francis
 
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.pdffasttrackscardecors
 
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.pdfalimacal
 
Railway reservation(c++ project)
Railway reservation(c++ project)Railway reservation(c++ project)
Railway reservation(c++ project)Debashis Rath
 
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...PVS-Studio
 

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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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 .pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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.pdfankit11134
 
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 .pdfankit11134
 

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

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Recently uploaded (20)

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

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);