Added basic server functionality from ex 2 lesson 11

This commit is contained in:
elvis
2022-03-09 19:24:49 +01:00
parent c0372c44e2
commit d0a4e4411e
9 changed files with 869 additions and 0 deletions

240
lib/threadpool/threadpool.c Normal file
View File

@ -0,0 +1,240 @@
/**
* @file threadpool.c
* @brief File di implementazione dell'interfaccia Threadpool
*/
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <util.h>
#include <threadpool.h>
/**
* @function void *threadpool_thread(void *threadpool)
* @brief funzione eseguita dal thread worker che appartiene al pool
*/
static void *workerpool_thread(void *threadpool) {
threadpool_t *pool = (threadpool_t *)threadpool; // cast
taskfun_t task; // generic task
pthread_t self = pthread_self();
int myid = -1;
// non efficiente, si puo' fare meglio.....
do {
for (int i=0;i<pool->numthreads;++i)
if (pthread_equal(pool->threads[i], self)) {
myid = i;
break;
}
} while (myid < 0);
LOCK_RETURN(&(pool->lock), NULL);
for (;;) {
// in attesa di un messaggio, controllo spurious wakeups.
while((pool->count == 0) && (!pool->exiting)) {
pthread_cond_wait(&(pool->cond), &(pool->lock));
}
if (pool->exiting > 1) break; // exit forzato, esco immediatamente
// devo uscire ma ci sono messaggi pendenti
if (pool->exiting == 1 && !pool->count) break;
// nuovo task
task.fun = pool->pending_queue[pool->head].fun;
task.arg = pool->pending_queue[pool->head].arg;
pool->head++; pool->count--;
pool->head = (pool->head == abs(pool->queue_size)) ? 0 : pool->head;
pool->taskonthefly++;
UNLOCK_RETURN(&(pool->lock), NULL);
// eseguo la funzione
(*(task.fun))(task.arg);
LOCK_RETURN(&(pool->lock), NULL);
pool->taskonthefly--;
}
UNLOCK_RETURN(&(pool->lock), NULL);
fprintf(stderr, "thread %d exiting\n", myid);
return NULL;
}
static int freePoolResources(threadpool_t *pool) {
if(pool->threads) {
free(pool->threads);
free(pool->pending_queue);
pthread_mutex_destroy(&(pool->lock));
pthread_cond_destroy(&(pool->cond));
}
free(pool);
return 0;
}
threadpool_t *createThreadPool(int numthreads, int pending_size) {
if(numthreads <= 0 || pending_size < 0) {
errno = EINVAL;
return NULL;
}
threadpool_t *pool = (threadpool_t *)malloc(sizeof(threadpool_t));
if (pool == NULL) return NULL;
// condizioni iniziali
pool->numthreads = 0;
pool->taskonthefly = 0;
pool->queue_size = (pending_size == 0 ? -1 : pending_size);
pool->head = pool->tail = pool->count = 0;
pool->exiting = 0;
/* Allocate thread and task queue */
pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * numthreads);
if (pool->threads == NULL) {
free(pool);
return NULL;
}
pool->pending_queue = (taskfun_t *)malloc(sizeof(taskfun_t) * abs(pool->queue_size));
if (pool->pending_queue == NULL) {
free(pool->threads);
free(pool);
return NULL;
}
if ((pthread_mutex_init(&(pool->lock), NULL) != 0) ||
(pthread_cond_init(&(pool->cond), NULL) != 0)) {
free(pool->threads);
free(pool->pending_queue);
free(pool);
return NULL;
}
for(int i = 0; i < numthreads; i++) {
if(pthread_create(&(pool->threads[i]), NULL,
workerpool_thread, (void*)pool) != 0) {
/* errore fatale, libero tutto forzando l'uscita dei threads */
destroyThreadPool(pool, 1);
errno = EFAULT;
return NULL;
}
pool->numthreads++;
}
return pool;
}
int destroyThreadPool(threadpool_t *pool, int force) {
if(pool == NULL || force < 0) {
errno = EINVAL;
return -1;
}
LOCK_RETURN(&(pool->lock), -1);
pool->exiting = 1 + force;
if (pthread_cond_broadcast(&(pool->cond)) != 0) {
UNLOCK_RETURN(&(pool->lock),-1);
errno = EFAULT;
return -1;
}
UNLOCK_RETURN(&(pool->lock), -1);
for(int i = 0; i < pool->numthreads; i++) {
if (pthread_join(pool->threads[i], NULL) != 0) {
errno = EFAULT;
UNLOCK_RETURN(&(pool->lock),-1);
return -1;
}
}
freePoolResources(pool);
return 0;
}
int addToThreadPool(threadpool_t *pool, void (*f)(void *), void *arg) {
if(pool == NULL || f == NULL) {
errno = EINVAL;
return -1;
}
LOCK_RETURN(&(pool->lock), -1);
int queue_size = abs(pool->queue_size);
int nopending = (pool->queue_size == -1); // non dobbiamo gestire messaggi pendenti
// coda piena o in fase di uscita
if (pool->count >= queue_size || pool->exiting) {
UNLOCK_RETURN(&(pool->lock),-1);
return 1; // esco con valore "coda piena"
}
if (pool->taskonthefly >= pool->numthreads) {
if (nopending) {
// tutti i thread sono occupati e non si gestiscono task pendenti
assert(pool->count == 0);
UNLOCK_RETURN(&(pool->lock),-1);
return 1; // esco con valore "coda piena"
}
}
pool->pending_queue[pool->tail].fun = f;
pool->pending_queue[pool->tail].arg = arg;
pool->count++;
pool->tail++;
if (pool->tail >= queue_size) pool->tail = 0;
int r;
if((r=pthread_cond_signal(&(pool->cond))) != 0) {
UNLOCK_RETURN(&(pool->lock),-1);
errno = r;
return -1;
}
UNLOCK_RETURN(&(pool->lock),-1);
return 0;
}
/**
* @function void *thread_proxy(void *argl)
* @brief funzione eseguita dal thread worker che non appartiene al pool
*/
static void *proxy_thread(void *arg) {
taskfun_t *task = (taskfun_t*)arg;
// eseguo la funzione
(*(task->fun))(task->arg);
free(task);
return NULL;
}
// fa lo spawn di un thread in modalità detached
int spawnThread(void (*f)(void*), void* arg) {
if (f == NULL) {
errno = EINVAL;
return -1;
}
taskfun_t *task = malloc(sizeof(taskfun_t)); // la memoria verra' liberata dal proxy
if (!task) return -1;
task->fun = f;
task->arg = arg;
pthread_t thread;
pthread_attr_t attr;
if (pthread_attr_init(&attr) != 0) return -1;
if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) return -1;
if (pthread_create(&thread, &attr,
proxy_thread, (void*)task) != 0) {
free(task);
errno = EFAULT;
return -1;
}
return 0;
}

View File

@ -0,0 +1,81 @@
#ifndef THREADPOOL_H_
#define THREADPOOL_H_
#include <pthread.h>
/**
* @file threadpool.h
* @brief Interfaccia per il ThreadPool
*/
/**
* @struct threafun_t
* @brief generico task che un thread del threadpool deve eseguire
*
* @var fun Puntatore alla funzione da eseguire
* @var arg Argomento della funzione
*/
typedef struct taskfun_t {
void (*fun)(void *);
void *arg;
} taskfun_t;
/**
* @struct threadpool
* @brief Rappresentazione dell'oggetto threadpool
*/
typedef struct threadpool_t {
pthread_mutex_t lock; // mutua esclusione nell'accesso all'oggetto
pthread_cond_t cond; // usata per notificare un worker thread
pthread_t * threads; // array di worker id
int numthreads; // numero di thread (size dell'array threads)
taskfun_t *pending_queue; // coda interna per task pendenti
int queue_size; // massima size della coda, puo' essere anche -1 ad indicare che non si vogliono gestire task pendenti
int taskonthefly; // numero di task attualmente in esecuzione
int head, tail; // riferimenti della coda
int count; // numero di task nella coda dei task pendenti
int exiting; // se > 0 e' iniziato il protocollo di uscita, se 1 il thread aspetta che non ci siano piu' lavori in coda
} threadpool_t;
/**
* @function createThreadPool
* @brief Crea un oggetto thread pool.
* @param numthreads è il numero di thread del pool
* @param pending_size è la size delle richieste che possono essere pendenti. Questo parametro è 0 se si vuole utilizzare un modello per il pool con 1 thread 1 richiesta, cioe' non ci sono richieste pendenti.
*
* @return un nuovo thread pool oppure NULL ed errno settato opportunamente
*/
threadpool_t *createThreadPool(int numthreads, int pending_size);
/**
* @function destroyThreadPool
* @brief stoppa tutti i thread e distrugge l'oggetto pool
* @param pool oggetto da liberare
* @param force se 1 forza l'uscita immediatamente di tutti i thread e libera subito le risorse, se 0 aspetta che i thread finiscano tutti e soli i lavori pendenti (non accetta altri lavori).
*
* @return 0 in caso di successo <0 in caso di fallimento ed errno viene settato opportunamente
*/
int destroyThreadPool(threadpool_t *pool, int force);
/**
* @function addTaskToThreadPool
* @brief aggiunge un task al pool, se ci sono thread liberi il task viene assegnato ad uno di questi, se non ci sono thread liberi e pending_size > 0 allora si cerca di inserire il task come task pendente. Se non c'e' posto nella coda interna allora la chiamata fallisce.
* @param pool oggetto thread pool
* @param fun funzione da eseguire per eseguire il task
* @param arg argomento della funzione
* @return 0 se successo, 1 se non ci sono thread disponibili e/o la coda è piena, -1 in caso di fallimento, errno viene settato opportunamente.
*/
int addToThreadPool(threadpool_t *pool, void (*fun)(void *),void *arg);
/**
* @function spawnThread
* @brief lancia un thread che esegue la funzione fun passata come parametro, il thread viene lanciato in modalità detached e non fa parte del pool.
* @param fun funzione da eseguire per eseguire il task
* @param arg argomento della funzione
* @return 0 se successo, -1 in caso di fallimento, errno viene settato opportunamente.
*/
int spawnThread(void (*f)(void*), void* arg);
#endif /* THREADPOOL_H_ */