Write a C program using Pthreads on Linux that acts like a countdown timer alarm
ID: 3819898 • Letter: W
Question
Write a C program using Pthreads on Linux that acts like a countdown timer alarm: The program implements a timer with two threads When the program starts, prompt the user for a number of seconds to set the timer (look into using scanf() to do this) Start two threads: 1. A thread that waits for a notification that the timer expired; when the timer expires, this thread should print a message that the timer has expired 2. A thread that will wait for the specified number of seconds (look into sleep() for this) and then sends a notification to the other thread that the timer has expired
Explanation / Answer
// Note: Please provide thumbs-up if you like the solution
// FileName: alarm_timer.c
// Follow below steps to run and see the output //
/*
$ gcc -o alarm_timer alarm_timer.c -lpthread
$ ./alarm_timer
Enter number of seconds to set timer:
2
go to sleep for 2 seconds ...
after go to sleep for seconds ...
Alarm bursted
$
*/
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t mutex1;
sem_t mutex2;
void *read_alarm(void* arg)
{
// call wait on mutex 1, this will allow thread to wait as initial value is 0, until post is called by start_alarm function
sem_wait(&mutex1);
printf("Alarm bursted ");
}
void *start_alarm(void* arg)
{
// call wait on mutex 2, this will allow thread to enter the critical section as initial value is 1
sem_wait(&mutex2);
int *seconds=(int*) arg;
printf("go to sleep for %d seconds ... ", *seconds);
sleep(*seconds);
printf("after go to sleep for seconds ... ");
sem_post(&mutex1);
}
int main()
{
int timer;
// initlizes semaphore with 0
sem_init(&mutex1,0,0);
// initlizes semaphore with 1
sem_init(&mutex2,0,1);
pthread_t tid[2];
printf("Enter number of seconds to set timer: ");
scanf("%d", &timer);
// creates a thread and call start_alarm, pass timer input by user
pthread_create(&tid[0], NULL, start_alarm, (void*)&timer);
// creates a thread and call read_alarm
pthread_create(&tid[1], NULL, read_alarm, (void*)&timer);
// call join on created threads
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
// call pthread_exit to wait till all threads have finished execution
pthread_exit(0);
// clean semaphores
sem_destroy(&mutex1);
sem_destroy(&mutex2);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.