#elif POOLSERVER
/*
* TODO: PART 7
*
* When a client connection has been accepted, add the
* client's socket number to the work queue. A thread
* in the thread pool will send a response to the client.
*/
typedef struct {
int *buf; // buffer to store client socket numbers
int capacity; // total capacity of the queue
int front; // index of the first element
int rear; // index immediately next to the last element
int count; // number of elements in the queue
pthread_mutex_t mutex; // mutex to protect the queue
pthread_cond_t not_empty; // conditional variable to signal a non-empty queue
pthread_cond_t not_full; // conditional variable to signal a non-full queue
} wq_t;
void wq_init(wq_t *wq, int capacity);
void wq_push(wq_t *wq, int socket);
int wq_pop(wq_t *wq);
void wq_destroy(wq_t *wq);
#include <stdlib.h>
#include <pthread.h>
#include "wq.h"
#define NUM_THREADS (--num-threads)
wq_t wq;
// Function to handle client request
void *handle_request(void *args) {
int client_socket = *((int *) args);
// Process client request here
// ...
close(client_socket);
return NULL;
}
int main(int argc, char *argv[]) {
// Initialize work queue
int num_threads = 4; // Number of threads in the thread pool
int capacity = 100; // Capacity of the work queue
wq_init(&wq, capacity);
// Create worker threads
pthread_t threads[num_threads];
for (int i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], NULL, handle_request, NULL);
}
// Accept client connections and add socket numbers to work queue
int server_socket;
// ...
while (1) {
int client_socket = accept(server_socket, NULL, NULL);
wq_push(&wq, client_socket);
}
// Wait for worker threads to finish
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
// Destroy work queue
wq_destroy(&wq);
return 0;
}