C Multi-threading Using Semaphores to Allow Multiple Processes Into the Critical
ID: 3844059 • Letter: C
Question
C Multi-threading Using Semaphores to Allow Multiple Processes Into the Critical Section:
Hello, I need a program that will generate 5 threads. 4 of them will be worker threads that have a message and a priority, and 1 of them will be a master thread that exists in the critical section to analyze the priority of the other 4 threads. All 5 threads will enter the critical section at once, and the master thread will then choose the thread with the highest priority. The other 3 threads are then kicked out of the critical section and the master thread prints out the message that the thread with the highest priority has.
This must be written using pthreads and semaphores. You must demonstrate that it works by providing an ouput of the master thread printing the message of the thread with the highest priority.
Input for each thread will be of the following format: ABCD
AB = message
C = priority (0-9, 0 being highest)
D = Thread ID (0-3).
The priorities cannot be the same.
Explanation / Answer
The main purpose of the Multithreading is executing from two or more operations in your program at the same time. For example, you want to operate a lenghty file download from the internet, but don’t want to keep the people waiting while this happens.
Lets talk about the ptheards and its structure before proceeding further:-
Syntax: #include <pthread.h>
--> It basically deals with various Pthreads functions, constants, types, etc.
Using Thread: int pthread_create (pthread_t * thread_p, const pthread_attr_t * attribute, void (*thread_function)(void *), void *arg_p);
Basic Overview about Semaphore:-
Syntax: #include <semaphore.h>
Initiaze: int sem_init(sem_t *sem, int pshared, unsigned int value);
Note: Kindly execute this program with the -pthread GCC option only.
Program:-
Firstly we will be adding the header files which requires in the execution of a program. For each header file, It is demonstrated and useful in respective manner.
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM 5
semaphore_t semp;
void* thread_f(void* param){
int id = (int) param;
/* It indicates the thread to sleep */
sem_wait(&semp);
printf("Thread %d is started working now ! ",id);
return NULL;
}
int main(){
pthread_t threads[NUM];
int i;
sem_init(&semp, 0, 0);
for (i=0;i<NUM;i++){
pthread_create(&threads[i],NULL,thread_f,(void *)i);
}
printf("Other Threads Kindly Wait. ");
sleep(1);
printf("Keep going! ");
/*It gives the wakeup call to the threads*/
for(i=0;i<NUM;i++)
sem_post(&semp);
/* It helps to give the chance to other remaining threads */
sleep(1);
printf("Main method is about to End.... ");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.