Skip to content
Snippets Groups Projects
Commit c40c5d48 authored by Max Barrett's avatar Max Barrett
Browse files

Only making one thread and getting stuck on a cond wait

parent 8d2fe0a4
No related branches found
No related tags found
No related merge requests found
......@@ -12,6 +12,7 @@ struct thread_pool {
struct list global_queue;
bool shutdown;
int threads;
struct worker *workers;
};
struct future {
......@@ -22,36 +23,50 @@ struct future {
};
struct worker {
struct thread_pool* pool;
struct thread_pool* worker_threadpool;
pthread_t internal;
};
static __thread struct worker* current_worker = NULL;
static void *start_routine(void * arg) {
struct worker *worker = (struct worker *) arg;
while (!worker->worker_threadpool->shutdown) {
pthread_mutex_lock(&worker->worker_threadpool->lock);
struct future *worker_future = list_entry(list_pop_front(&worker->worker_threadpool->global_queue), struct future, elem);
if (list_empty(&worker->worker_threadpool->global_queue)) {
pthread_cond_wait(&worker->worker_threadpool->cond, &worker->worker_threadpool->lock);
}
worker_future->result = worker_future->task(worker->worker_threadpool, worker_future->args);
}
pthread_mutex_unlock(&worker->worker_threadpool->lock);
return NULL;
}
struct thread_pool * thread_pool_new(int nthreads) {
struct thread_pool *threadpool = malloc(sizeof(struct thread_pool));
threadpool->threads = nthreads;
pthread_cond_init(&threadpool->cond, NULL);
pthread_mutex_init(&threadpool->lock, NULL);
list_init(&threadpool->global_queue);
threadpool->workers = malloc(sizeof(struct worker) * nthreads);
for (int i = 0; i < nthreads; i++) {
pool->workers[i].pool = pool;
pool->workers[i].index = i;
list_init(&pool->workers[i].deque);
pthread_create(&pool->workers[i].internal, NULL, start_routine, &pool->workers[i]);
threadpool->workers[i].worker_threadpool = threadpool;
pthread_create(&threadpool->workers[i].internal, NULL, start_routine, &threadpool->workers[i]);
}
return threadpool;
}
void thread_pool_shutdown_and_destroy(struct thread_pool *threadpool) {
pthread_mutex_lock(&threadpool->lock);
threadpool->shutdown = true;
return;
pthread_cond_broadcast(&threadpool->cond);
pthread_mutex_unlock(&threadpool->lock);
for (int i = 0; i < threadpool->threads; i++) {
printf("%d\n", i);
pthread_join(threadpool->workers[i].internal, NULL);
}
}
void * future_get(struct future *future) {
pthread_mutex_unlock(&pool->lock);
future->result = future->task(pool, future->args);
pthread_mutex_lock(&pool->lock);
return future;
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment