SlideShare a Scribd company logo
1 of 5
Download to read offline
This is a roller coaster C file program. Please correct my code, I am receiving a segmentation fault
from something in one of the functions! Here is the code I have right now: I believe the error is
coming from the car thread function. The instructions are below this 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 error checking in the command line argument works properly, but the program will not execute
and will print out a segmentation fault (core dumped). I have commented out main and there is
nothing wrong with the main function, I believe it may be something in the semaphores or the
conditionals in the car thread function. The output of the code must match the green and red text
above when inputting: ./roller -n 5 -c 2 -i 5 in the command line.
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 This is a roller coaster C file program Please correct my c.pdf

I need help to modify my code according to the instructions- Modify th.pdf
I need help to modify my code according to the instructions- Modify th.pdfI need help to modify my code according to the instructions- Modify th.pdf
I need help to modify my code according to the instructions- Modify th.pdfpnaran46
 
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
 
#include iostream #include string #include fstream std.docx
#include iostream #include string #include fstream  std.docx#include iostream #include string #include fstream  std.docx
#include iostream #include string #include fstream std.docxajoy21
 
C++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+OperatorsC++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+OperatorsMohammad Shaker
 
cbse 12 computer science IP
cbse 12 computer science IPcbse 12 computer science IP
cbse 12 computer science IPD. j Vicky
 
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
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statementsMomenMostafa
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)yap_raiza
 
12th CBSE Practical File
12th CBSE Practical File12th CBSE Practical File
12th CBSE Practical FileAshwin Francis
 
Animating angular applications
Animating angular applicationsAnimating angular applications
Animating angular applicationsTomek Sułkowski
 
Functions of stdio conio
Functions of stdio   conio Functions of stdio   conio
Functions of stdio conio Bhavik Vashi
 

Similar to This is a roller coaster C file program Please correct my c.pdf (20)

CP Handout#5
CP Handout#5CP Handout#5
CP Handout#5
 
I need help to modify my code according to the instructions- Modify th.pdf
I need help to modify my code according to the instructions- Modify th.pdfI need help to modify my code according to the instructions- Modify th.pdf
I need help to modify my code according to the instructions- Modify th.pdf
 
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...
 
#include iostream #include string #include fstream std.docx
#include iostream #include string #include fstream  std.docx#include iostream #include string #include fstream  std.docx
#include iostream #include string #include fstream std.docx
 
C++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+OperatorsC++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+Operators
 
Useful c programs
Useful c programsUseful c programs
Useful c programs
 
cbse 12 computer science IP
cbse 12 computer science IPcbse 12 computer science IP
cbse 12 computer science IP
 
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
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
 
week-3x
week-3xweek-3x
week-3x
 
12th CBSE Practical File
12th CBSE Practical File12th CBSE Practical File
12th CBSE Practical File
 
Animating angular applications
Animating angular applicationsAnimating angular applications
Animating angular applications
 
UNIT-II CP DOC.docx
UNIT-II CP DOC.docxUNIT-II CP DOC.docx
UNIT-II CP DOC.docx
 
2 data and c
2 data and c2 data and c
2 data and c
 
Functions of stdio conio
Functions of stdio   conio Functions of stdio   conio
Functions of stdio conio
 
Code optimization
Code optimization Code optimization
Code optimization
 
Code optimization
Code optimization Code optimization
Code optimization
 
SUMO simulation CODES AND STEPS
SUMO simulation CODES AND STEPSSUMO simulation CODES AND STEPS
SUMO simulation CODES AND STEPS
 
Presentation1
Presentation1Presentation1
Presentation1
 

More from adinathfashion1

This is based on lab activity in week 34 You will explore t.pdf
This is based on lab activity in week 34 You will explore t.pdfThis is based on lab activity in week 34 You will explore t.pdf
This is based on lab activity in week 34 You will explore t.pdfadinathfashion1
 
This is my visual studio C code how do I make it so that w.pdf
This is my visual studio C code how do I make it so that w.pdfThis is my visual studio C code how do I make it so that w.pdf
This is my visual studio C code how do I make it so that w.pdfadinathfashion1
 
This problem is referred to as Exon chaining in bioinformati.pdf
This problem is referred to as Exon chaining in bioinformati.pdfThis problem is referred to as Exon chaining in bioinformati.pdf
This problem is referred to as Exon chaining in bioinformati.pdfadinathfashion1
 
This project is broken up into Windows and Mac versions lis.pdf
This project is broken up into Windows and Mac versions lis.pdfThis project is broken up into Windows and Mac versions lis.pdf
This project is broken up into Windows and Mac versions lis.pdfadinathfashion1
 
Tim and Stephanie are devastated when they find out their ne.pdf
Tim and Stephanie are devastated when they find out their ne.pdfTim and Stephanie are devastated when they find out their ne.pdf
Tim and Stephanie are devastated when they find out their ne.pdfadinathfashion1
 
THis is from an Applied Mixed Models class Answer just part.pdf
THis is from an Applied Mixed Models class Answer just part.pdfTHis is from an Applied Mixed Models class Answer just part.pdf
THis is from an Applied Mixed Models class Answer just part.pdfadinathfashion1
 
This is not working for me at allAnd I cannot edit anythi.pdf
This is not working for me at allAnd I cannot edit anythi.pdfThis is not working for me at allAnd I cannot edit anythi.pdf
This is not working for me at allAnd I cannot edit anythi.pdfadinathfashion1
 
This is false please explain Assuming that the reserve req.pdf
This is false please explain Assuming that the reserve req.pdfThis is false please explain Assuming that the reserve req.pdf
This is false please explain Assuming that the reserve req.pdfadinathfashion1
 
This is NOT TRUE concerning courtship sounds Question 2 opt.pdf
This is NOT TRUE concerning courtship sounds Question 2 opt.pdfThis is NOT TRUE concerning courtship sounds Question 2 opt.pdf
This is NOT TRUE concerning courtship sounds Question 2 opt.pdfadinathfashion1
 
This is what I got for 54 but Im unsure if its right Prepa.pdf
This is what I got for 54 but Im unsure if its right Prepa.pdfThis is what I got for 54 but Im unsure if its right Prepa.pdf
This is what I got for 54 but Im unsure if its right Prepa.pdfadinathfashion1
 
This PNF technique starts with the same process as the the h.pdf
This PNF technique starts with the same process as the the h.pdfThis PNF technique starts with the same process as the the h.pdf
This PNF technique starts with the same process as the the h.pdfadinathfashion1
 
This is where you set up the project infrastructure to help .pdf
This is where you set up the project infrastructure to help .pdfThis is where you set up the project infrastructure to help .pdf
This is where you set up the project infrastructure to help .pdfadinathfashion1
 
This is a true case study A woman kept coming to the doctor.pdf
This is a true case study A woman kept coming to the doctor.pdfThis is a true case study A woman kept coming to the doctor.pdf
This is a true case study A woman kept coming to the doctor.pdfadinathfashion1
 
To answer Questions 14 and 15 read the article Britain.pdf
To answer Questions 14 and 15 read the article Britain.pdfTo answer Questions 14 and 15 read the article Britain.pdf
To answer Questions 14 and 15 read the article Britain.pdfadinathfashion1
 
To adhere to Endangered Species Act ESA guidelines the Fi.pdf
To adhere to Endangered Species Act ESA guidelines the Fi.pdfTo adhere to Endangered Species Act ESA guidelines the Fi.pdf
To adhere to Endangered Species Act ESA guidelines the Fi.pdfadinathfashion1
 
Title Media culture Objectives 1 To apply aseptic techniq.pdf
Title Media culture Objectives 1 To apply aseptic techniq.pdfTitle Media culture Objectives 1 To apply aseptic techniq.pdf
Title Media culture Objectives 1 To apply aseptic techniq.pdfadinathfashion1
 
TitleInvestigating the effect of counterfeit permits on the.pdf
TitleInvestigating the effect of counterfeit permits on the.pdfTitleInvestigating the effect of counterfeit permits on the.pdf
TitleInvestigating the effect of counterfeit permits on the.pdfadinathfashion1
 
Tketici talebindeki kk deiiklikler aadaki nedenlerle ve.pdf
Tketici talebindeki kk deiiklikler aadaki nedenlerle ve.pdfTketici talebindeki kk deiiklikler aadaki nedenlerle ve.pdf
Tketici talebindeki kk deiiklikler aadaki nedenlerle ve.pdfadinathfashion1
 
Titanic Project Management Blunders Links to an external s.pdf
Titanic  Project Management Blunders Links to an external s.pdfTitanic  Project Management Blunders Links to an external s.pdf
Titanic Project Management Blunders Links to an external s.pdfadinathfashion1
 
This is my table met Mry anlea Nole isch studein las diru ev.pdf
This is my table met Mry anlea Nole isch studein las diru ev.pdfThis is my table met Mry anlea Nole isch studein las diru ev.pdf
This is my table met Mry anlea Nole isch studein las diru ev.pdfadinathfashion1
 

More from adinathfashion1 (20)

This is based on lab activity in week 34 You will explore t.pdf
This is based on lab activity in week 34 You will explore t.pdfThis is based on lab activity in week 34 You will explore t.pdf
This is based on lab activity in week 34 You will explore t.pdf
 
This is my visual studio C code how do I make it so that w.pdf
This is my visual studio C code how do I make it so that w.pdfThis is my visual studio C code how do I make it so that w.pdf
This is my visual studio C code how do I make it so that w.pdf
 
This problem is referred to as Exon chaining in bioinformati.pdf
This problem is referred to as Exon chaining in bioinformati.pdfThis problem is referred to as Exon chaining in bioinformati.pdf
This problem is referred to as Exon chaining in bioinformati.pdf
 
This project is broken up into Windows and Mac versions lis.pdf
This project is broken up into Windows and Mac versions lis.pdfThis project is broken up into Windows and Mac versions lis.pdf
This project is broken up into Windows and Mac versions lis.pdf
 
Tim and Stephanie are devastated when they find out their ne.pdf
Tim and Stephanie are devastated when they find out their ne.pdfTim and Stephanie are devastated when they find out their ne.pdf
Tim and Stephanie are devastated when they find out their ne.pdf
 
THis is from an Applied Mixed Models class Answer just part.pdf
THis is from an Applied Mixed Models class Answer just part.pdfTHis is from an Applied Mixed Models class Answer just part.pdf
THis is from an Applied Mixed Models class Answer just part.pdf
 
This is not working for me at allAnd I cannot edit anythi.pdf
This is not working for me at allAnd I cannot edit anythi.pdfThis is not working for me at allAnd I cannot edit anythi.pdf
This is not working for me at allAnd I cannot edit anythi.pdf
 
This is false please explain Assuming that the reserve req.pdf
This is false please explain Assuming that the reserve req.pdfThis is false please explain Assuming that the reserve req.pdf
This is false please explain Assuming that the reserve req.pdf
 
This is NOT TRUE concerning courtship sounds Question 2 opt.pdf
This is NOT TRUE concerning courtship sounds Question 2 opt.pdfThis is NOT TRUE concerning courtship sounds Question 2 opt.pdf
This is NOT TRUE concerning courtship sounds Question 2 opt.pdf
 
This is what I got for 54 but Im unsure if its right Prepa.pdf
This is what I got for 54 but Im unsure if its right Prepa.pdfThis is what I got for 54 but Im unsure if its right Prepa.pdf
This is what I got for 54 but Im unsure if its right Prepa.pdf
 
This PNF technique starts with the same process as the the h.pdf
This PNF technique starts with the same process as the the h.pdfThis PNF technique starts with the same process as the the h.pdf
This PNF technique starts with the same process as the the h.pdf
 
This is where you set up the project infrastructure to help .pdf
This is where you set up the project infrastructure to help .pdfThis is where you set up the project infrastructure to help .pdf
This is where you set up the project infrastructure to help .pdf
 
This is a true case study A woman kept coming to the doctor.pdf
This is a true case study A woman kept coming to the doctor.pdfThis is a true case study A woman kept coming to the doctor.pdf
This is a true case study A woman kept coming to the doctor.pdf
 
To answer Questions 14 and 15 read the article Britain.pdf
To answer Questions 14 and 15 read the article Britain.pdfTo answer Questions 14 and 15 read the article Britain.pdf
To answer Questions 14 and 15 read the article Britain.pdf
 
To adhere to Endangered Species Act ESA guidelines the Fi.pdf
To adhere to Endangered Species Act ESA guidelines the Fi.pdfTo adhere to Endangered Species Act ESA guidelines the Fi.pdf
To adhere to Endangered Species Act ESA guidelines the Fi.pdf
 
Title Media culture Objectives 1 To apply aseptic techniq.pdf
Title Media culture Objectives 1 To apply aseptic techniq.pdfTitle Media culture Objectives 1 To apply aseptic techniq.pdf
Title Media culture Objectives 1 To apply aseptic techniq.pdf
 
TitleInvestigating the effect of counterfeit permits on the.pdf
TitleInvestigating the effect of counterfeit permits on the.pdfTitleInvestigating the effect of counterfeit permits on the.pdf
TitleInvestigating the effect of counterfeit permits on the.pdf
 
Tketici talebindeki kk deiiklikler aadaki nedenlerle ve.pdf
Tketici talebindeki kk deiiklikler aadaki nedenlerle ve.pdfTketici talebindeki kk deiiklikler aadaki nedenlerle ve.pdf
Tketici talebindeki kk deiiklikler aadaki nedenlerle ve.pdf
 
Titanic Project Management Blunders Links to an external s.pdf
Titanic  Project Management Blunders Links to an external s.pdfTitanic  Project Management Blunders Links to an external s.pdf
Titanic Project Management Blunders Links to an external s.pdf
 
This is my table met Mry anlea Nole isch studein las diru ev.pdf
This is my table met Mry anlea Nole isch studein las diru ev.pdfThis is my table met Mry anlea Nole isch studein las diru ev.pdf
This is my table met Mry anlea Nole isch studein las diru ev.pdf
 

Recently uploaded

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
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
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
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
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
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
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).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
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

This is a roller coaster C file program Please correct my c.pdf

  • 1. This is a roller coaster C file program. Please correct my code, I am receiving a segmentation fault from something in one of the functions! Here is the code I have right now: I believe the error is coming from the car thread function. The instructions are below this 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); }
  • 2. //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;
  • 3. } 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]);
  • 4. //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.
  • 5. 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 error checking in the command line argument works properly, but the program will not execute and will print out a segmentation fault (core dumped). I have commented out main and there is nothing wrong with the main function, I believe it may be something in the semaphores or the conditionals in the car thread function. The output of the code must match the green and red text above when inputting: ./roller -n 5 -c 2 -i 5 in the command line. 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);