45 pool->max_threads = max; |
45 pool->max_threads = max; |
46 pool->num_threads = 0; |
46 pool->num_threads = 0; |
47 |
47 |
48 pthread_mutex_init(&pool->queue_lock, NULL); |
48 pthread_mutex_init(&pool->queue_lock, NULL); |
49 pthread_mutex_init(&pool->avlbl_lock, NULL); |
49 pthread_mutex_init(&pool->avlbl_lock, NULL); |
50 pthread_cond_init(&pool->available, NULL); |
50 pthread_cond_init(&pool->available, NULL); |
51 |
51 |
|
52 return pool; |
|
53 } |
|
54 |
|
55 int threadpool_start(threadpool_t *pool) { |
52 /* create pool threads */ |
56 /* create pool threads */ |
53 for(int i=0;i<min;i++) { |
57 for(int i=0;i<pool->min_threads;i++) { |
54 pthread_t t; |
58 pthread_t t; |
55 if (pthread_create(&t, NULL, threadpool_func, pool) != 0) { |
59 if (pthread_create(&t, NULL, threadpool_func, pool) != 0) { |
56 perror("Error: threadpool_new: pthread_create"); |
60 perror("Error: threadpool_start: pthread_create"); |
57 return NULL; |
61 return 1; |
58 } |
62 } |
59 } |
63 } |
60 |
64 return 0; |
61 return pool; |
|
62 } |
65 } |
63 |
66 |
64 void* threadpool_func(void *data) { |
67 void* threadpool_func(void *data) { |
65 threadpool_t *pool = (threadpool_t*)data; |
68 threadpool_t *pool = (threadpool_t*)data; |
66 |
69 |
101 pthread_mutex_unlock(&pool->queue_lock); |
104 pthread_mutex_unlock(&pool->queue_lock); |
102 return job; |
105 return job; |
103 } |
106 } |
104 |
107 |
105 void threadpool_run(threadpool_t *pool, job_callback_f func, void *data) { |
108 void threadpool_run(threadpool_t *pool, job_callback_f func, void *data) { |
|
109 // TODO: handle errors |
|
110 |
|
111 if(pool->num_threads == 0) { |
|
112 threadpool_start(pool); |
|
113 } |
|
114 |
106 threadpool_job *job = malloc(sizeof(threadpool_job)); |
115 threadpool_job *job = malloc(sizeof(threadpool_job)); |
107 job->callback = func; |
116 job->callback = func; |
108 job->data = data; |
117 job->data = data; |
109 |
118 |
110 pthread_mutex_lock(&pool->queue_lock); |
119 pthread_mutex_lock(&pool->queue_lock); |