Question
Programming language:C; Multi-threaded Server - Mutexes - Semaphores Modify the multi-threaded server (file server.c) such that it is created with a pool of N threads
Programming language:C;
Multi-threaded Server - Mutexes - Semaphores
Modify the multi-threaded server (file server.c) such that it is created with a pool of N threads and a buffer of M ints. The sever validates the argument: $ ./server usage: ./server N-threads M-items When the buffer has reached its full capacity, inputs are ignored until room is available. In the following scenario, inputs 5 and 6 are lost because the buffer is full: $ ./server 2 2 *** 2 threads, 2 buffered items 1 2 Processing: 1 Processing: 2 3 4 5 6 buffer is full! buffer is full! Done with: 1 Processing: 3 Done with: 2 Processing: 4 7 Done with: 3 Processing: 7 Done with: 4 Done with: 7 Here is another normal execution: ./server 5 10 *** 5 threads, 10 buffered items 1 2 3 4 5 1 Processing: 1 Processing: 2 Processing: 3 Processing: 4 Processing: 5 6 7 8 9 10 11 12 13 14 15 Done with: 1 Done with: 2 Processing: 7 Done with: 3 Done with: 5 Processing: 8 Processing: 6 Processing: 9 Done with: 4 Processing: 10 Done with: 7 Done with: 9 Processing: 12 Processing: 11 Done with: 6 Processing: 13 Done with: 8 Processing: 14 Done with: 10 Processing: 15 Done with: 12 Done with: 11 Done with: 13 Done with: 14 Done with: 1
-------------------------------------------
server.c:
#include
#define N 2 // number of threads volatile int buffer; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; // for buffer access sem_t semaphore; // controls the pool of threads
static void * worker(void *arg) { // input int j; while (true) { // block until work is available if (sem_wait(&semaphore)) { fprintf(stderr, "sem_wait: %s ", strerror(errno)); exit(EXIT_FAILURE); } // get exclusive access to buffer if (pthread_mutex_lock(&mtx)) { fprintf(stderr, "pthread_mutex_lock: %s ", strerror(errno)); exit(EXIT_FAILURE); } // store input j = buffer; // release exclusive access to buffer if (pthread_mutex_unlock(&mtx)) { fprintf(stderr, "pthread_mutex_unlock: %s ", strerror(errno)); exit(EXIT_FAILURE); } // process data fprintf(stdout, "Processing: %d ", j); sleep(10); fprintf(stdout, "Done with: %d ", j); } }
int main() { // input int j; // initialize semaphore if (sem_init(&semaphore, 0, 0)) { fprintf(stderr, "sem_init: %s ", strerror(errno)); exit(EXIT_FAILURE); } // create pool of N detached threads pthread_t t; for (int i=0; i
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started