thpool.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /* ********************************
  2. * Author: Johan Hanssen Seferidis
  3. * License: MIT
  4. * Description: Library providing a threading pool where you can add
  5. * work. For usage, check the thpool.h file or README.md
  6. *
  7. *//** @file thpool.h *//*
  8. *
  9. ********************************/
  10. #if defined(__APPLE__)
  11. #include <AvailabilityMacros.h>
  12. #else
  13. #ifndef _POSIX_C_SOURCE
  14. #define _POSIX_C_SOURCE 200809L
  15. #endif
  16. #endif
  17. #include <unistd.h>
  18. #include <signal.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <pthread.h>
  22. #include <errno.h>
  23. #include <time.h>
  24. #if defined(__linux__)
  25. #include <sys/prctl.h>
  26. #endif
  27. #include "thpool.h"
  28. #ifdef THPOOL_DEBUG
  29. #define THPOOL_DEBUG 1
  30. #else
  31. #define THPOOL_DEBUG 0
  32. #endif
  33. #if !defined(DISABLE_PRINT) || defined(THPOOL_DEBUG)
  34. #define err(str) fprintf(stderr, str)
  35. #else
  36. #define err(str)
  37. #endif
  38. static volatile int threads_keepalive;
  39. static volatile int threads_on_hold;
  40. /* ========================== STRUCTURES ============================ */
  41. /* Binary semaphore */
  42. typedef struct bsem {
  43. pthread_mutex_t mutex;
  44. pthread_cond_t cond;
  45. int v;
  46. } bsem;
  47. /* Job */
  48. typedef struct job{
  49. struct job* prev; /* pointer to previous job */
  50. void (*function)(void* arg); /* function pointer */
  51. void* arg; /* function's argument */
  52. } job;
  53. /* Job queue */
  54. typedef struct jobqueue{
  55. pthread_mutex_t rwmutex; /* used for queue r/w access */
  56. job *front; /* pointer to front of queue */
  57. job *rear; /* pointer to rear of queue */
  58. bsem *has_jobs; /* flag as binary semaphore */
  59. int len; /* number of jobs in queue */
  60. } jobqueue;
  61. /* Thread */
  62. typedef struct thread{
  63. int id; /* friendly id */
  64. pthread_t pthread; /* pointer to actual thread */
  65. struct thpool_* thpool_p; /* access to thpool */
  66. } thread;
  67. /* Threadpool */
  68. typedef struct thpool_{
  69. thread** threads; /* pointer to threads */
  70. volatile int num_threads_alive; /* threads currently alive */
  71. volatile int num_threads_working; /* threads currently working */
  72. pthread_mutex_t thcount_lock; /* used for thread count etc */
  73. pthread_cond_t threads_all_idle; /* signal to thpool_wait */
  74. jobqueue jobqueue; /* job queue */
  75. } thpool_;
  76. /* ========================== PROTOTYPES ============================ */
  77. static int thread_init(thpool_* thpool_p, struct thread** thread_p, int id);
  78. static void* thread_do(struct thread* thread_p);
  79. static void thread_hold(int sig_id);
  80. static void thread_destroy(struct thread* thread_p);
  81. static int jobqueue_init(jobqueue* jobqueue_p);
  82. static void jobqueue_clear(jobqueue* jobqueue_p);
  83. static void jobqueue_push(jobqueue* jobqueue_p, struct job* newjob_p);
  84. static struct job* jobqueue_pull(jobqueue* jobqueue_p);
  85. static void jobqueue_destroy(jobqueue* jobqueue_p);
  86. static void bsem_init(struct bsem *bsem_p, int value);
  87. static void bsem_reset(struct bsem *bsem_p);
  88. static void bsem_post(struct bsem *bsem_p);
  89. static void bsem_post_all(struct bsem *bsem_p);
  90. static void bsem_wait(struct bsem *bsem_p);
  91. /* ========================== THREADPOOL ============================ */
  92. /* Initialise thread pool */
  93. struct thpool_* thpool_init(int num_threads){
  94. threads_on_hold = 0;
  95. threads_keepalive = 1;
  96. if (num_threads < 0){
  97. num_threads = 0;
  98. }
  99. /* Make new thread pool */
  100. thpool_* thpool_p;
  101. thpool_p = (struct thpool_*)malloc(sizeof(struct thpool_));
  102. if (thpool_p == NULL){
  103. err("thpool_init(): Could not allocate memory for thread pool\n");
  104. return NULL;
  105. }
  106. thpool_p->num_threads_alive = 0;
  107. thpool_p->num_threads_working = 0;
  108. /* Initialise the job queue */
  109. if (jobqueue_init(&thpool_p->jobqueue) == -1){
  110. err("thpool_init(): Could not allocate memory for job queue\n");
  111. free(thpool_p);
  112. return NULL;
  113. }
  114. /* Make threads in pool */
  115. thpool_p->threads = (struct thread**)malloc(num_threads * sizeof(struct thread *));
  116. if (thpool_p->threads == NULL){
  117. err("thpool_init(): Could not allocate memory for threads\n");
  118. jobqueue_destroy(&thpool_p->jobqueue);
  119. free(thpool_p);
  120. return NULL;
  121. }
  122. pthread_mutex_init(&(thpool_p->thcount_lock), NULL);
  123. pthread_cond_init(&thpool_p->threads_all_idle, NULL);
  124. /* Thread init */
  125. int n;
  126. for (n=0; n<num_threads; n++){
  127. thread_init(thpool_p, &thpool_p->threads[n], n);
  128. #if THPOOL_DEBUG
  129. printf("THPOOL_DEBUG: Created thread %d in pool \n", n);
  130. #endif
  131. }
  132. /* Wait for threads to initialize */
  133. while (thpool_p->num_threads_alive != num_threads) {}
  134. return thpool_p;
  135. }
  136. /* Add work to the thread pool */
  137. int thpool_add_work(thpool_* thpool_p, void (*function_p)(void*), void* arg_p){
  138. job* newjob;
  139. newjob=(struct job*)malloc(sizeof(struct job));
  140. if (newjob==NULL){
  141. err("thpool_add_work(): Could not allocate memory for new job\n");
  142. return -1;
  143. }
  144. /* add function and argument */
  145. newjob->function=function_p;
  146. newjob->arg=arg_p;
  147. /* add job to queue */
  148. jobqueue_push(&thpool_p->jobqueue, newjob);
  149. return 0;
  150. }
  151. /* Wait until all jobs have finished */
  152. void thpool_wait(thpool_* thpool_p){
  153. pthread_mutex_lock(&thpool_p->thcount_lock);
  154. while (thpool_p->jobqueue.len || thpool_p->num_threads_working) {
  155. pthread_cond_wait(&thpool_p->threads_all_idle, &thpool_p->thcount_lock);
  156. }
  157. pthread_mutex_unlock(&thpool_p->thcount_lock);
  158. }
  159. /* Destroy the threadpool */
  160. void thpool_destroy(thpool_* thpool_p){
  161. /* No need to destory if it's NULL */
  162. if (thpool_p == NULL) return ;
  163. volatile int threads_total = thpool_p->num_threads_alive;
  164. /* End each thread 's infinite loop */
  165. threads_keepalive = 0;
  166. /* Give one second to kill idle threads */
  167. double TIMEOUT = 1.0;
  168. time_t start, end;
  169. double tpassed = 0.0;
  170. time (&start);
  171. while (tpassed < TIMEOUT && thpool_p->num_threads_alive){
  172. bsem_post_all(thpool_p->jobqueue.has_jobs);
  173. time (&end);
  174. tpassed = difftime(end,start);
  175. }
  176. /* Poll remaining threads */
  177. while (thpool_p->num_threads_alive){
  178. bsem_post_all(thpool_p->jobqueue.has_jobs);
  179. sleep(1);
  180. }
  181. /* Job queue cleanup */
  182. jobqueue_destroy(&thpool_p->jobqueue);
  183. /* Deallocs */
  184. int n;
  185. for (n=0; n < threads_total; n++){
  186. thread_destroy(thpool_p->threads[n]);
  187. }
  188. free(thpool_p->threads);
  189. free(thpool_p);
  190. }
  191. /* Pause all threads in threadpool */
  192. void thpool_pause(thpool_* thpool_p) {
  193. int n;
  194. for (n=0; n < thpool_p->num_threads_alive; n++){
  195. pthread_kill(thpool_p->threads[n]->pthread, SIGUSR1);
  196. }
  197. }
  198. /* Resume all threads in threadpool */
  199. void thpool_resume(thpool_* thpool_p) {
  200. // resuming a single threadpool hasn't been
  201. // implemented yet, meanwhile this supresses
  202. // the warnings
  203. (void)thpool_p;
  204. threads_on_hold = 0;
  205. }
  206. int thpool_num_threads_working(thpool_* thpool_p){
  207. return thpool_p->num_threads_working;
  208. }
  209. /* ============================ THREAD ============================== */
  210. /* Initialize a thread in the thread pool
  211. *
  212. * @param thread address to the pointer of the thread to be created
  213. * @param id id to be given to the thread
  214. * @return 0 on success, -1 otherwise.
  215. */
  216. static int thread_init (thpool_* thpool_p, struct thread** thread_p, int id){
  217. *thread_p = (struct thread*)malloc(sizeof(struct thread));
  218. if (*thread_p == NULL){
  219. err("thread_init(): Could not allocate memory for thread\n");
  220. return -1;
  221. }
  222. (*thread_p)->thpool_p = thpool_p;
  223. (*thread_p)->id = id;
  224. pthread_create(&(*thread_p)->pthread, NULL, (void * (*)(void *)) thread_do, (*thread_p));
  225. pthread_detach((*thread_p)->pthread);
  226. return 0;
  227. }
  228. /* Sets the calling thread on hold */
  229. static void thread_hold(int sig_id) {
  230. (void)sig_id;
  231. threads_on_hold = 1;
  232. while (threads_on_hold){
  233. sleep(1);
  234. }
  235. }
  236. /* What each thread is doing
  237. *
  238. * In principle this is an endless loop. The only time this loop gets interuppted is once
  239. * thpool_destroy() is invoked or the program exits.
  240. *
  241. * @param thread thread that will run this function
  242. * @return nothing
  243. */
  244. static void* thread_do(struct thread* thread_p){
  245. /* Set thread name for profiling and debuging */
  246. char thread_name[16] = {0};
  247. snprintf(thread_name, 16, "thpool-%d", thread_p->id);
  248. #if defined(__linux__)
  249. /* Use prctl instead to prevent using _GNU_SOURCE flag and implicit declaration */
  250. prctl(PR_SET_NAME, thread_name);
  251. #elif defined(__APPLE__) && defined(__MACH__)
  252. pthread_setname_np(thread_name);
  253. #else
  254. err("thread_do(): pthread_setname_np is not supported on this system");
  255. #endif
  256. /* Assure all threads have been created before starting serving */
  257. thpool_* thpool_p = thread_p->thpool_p;
  258. /* Register signal handler */
  259. struct sigaction act;
  260. sigemptyset(&act.sa_mask);
  261. act.sa_flags = SA_ONSTACK;
  262. act.sa_handler = thread_hold;
  263. if (sigaction(SIGUSR1, &act, NULL) == -1) {
  264. err("thread_do(): cannot handle SIGUSR1");
  265. }
  266. /* Mark thread as alive (initialized) */
  267. pthread_mutex_lock(&thpool_p->thcount_lock);
  268. thpool_p->num_threads_alive += 1;
  269. pthread_mutex_unlock(&thpool_p->thcount_lock);
  270. while(threads_keepalive){
  271. bsem_wait(thpool_p->jobqueue.has_jobs);
  272. if (threads_keepalive){
  273. pthread_mutex_lock(&thpool_p->thcount_lock);
  274. thpool_p->num_threads_working++;
  275. pthread_mutex_unlock(&thpool_p->thcount_lock);
  276. /* Read job from queue and execute it */
  277. void (*func_buff)(void*);
  278. void* arg_buff;
  279. job* job_p = jobqueue_pull(&thpool_p->jobqueue);
  280. if (job_p) {
  281. func_buff = job_p->function;
  282. arg_buff = job_p->arg;
  283. func_buff(arg_buff);
  284. free(job_p);
  285. }
  286. pthread_mutex_lock(&thpool_p->thcount_lock);
  287. thpool_p->num_threads_working--;
  288. if (!thpool_p->num_threads_working) {
  289. pthread_cond_signal(&thpool_p->threads_all_idle);
  290. }
  291. pthread_mutex_unlock(&thpool_p->thcount_lock);
  292. }
  293. }
  294. pthread_mutex_lock(&thpool_p->thcount_lock);
  295. thpool_p->num_threads_alive --;
  296. pthread_mutex_unlock(&thpool_p->thcount_lock);
  297. return NULL;
  298. }
  299. /* Frees a thread */
  300. static void thread_destroy (thread* thread_p){
  301. free(thread_p);
  302. }
  303. /* ============================ JOB QUEUE =========================== */
  304. /* Initialize queue */
  305. static int jobqueue_init(jobqueue* jobqueue_p){
  306. jobqueue_p->len = 0;
  307. jobqueue_p->front = NULL;
  308. jobqueue_p->rear = NULL;
  309. jobqueue_p->has_jobs = (struct bsem*)malloc(sizeof(struct bsem));
  310. if (jobqueue_p->has_jobs == NULL){
  311. return -1;
  312. }
  313. pthread_mutex_init(&(jobqueue_p->rwmutex), NULL);
  314. bsem_init(jobqueue_p->has_jobs, 0);
  315. return 0;
  316. }
  317. /* Clear the queue */
  318. static void jobqueue_clear(jobqueue* jobqueue_p){
  319. while(jobqueue_p->len){
  320. free(jobqueue_pull(jobqueue_p));
  321. }
  322. jobqueue_p->front = NULL;
  323. jobqueue_p->rear = NULL;
  324. bsem_reset(jobqueue_p->has_jobs);
  325. jobqueue_p->len = 0;
  326. }
  327. /* Add (allocated) job to queue
  328. */
  329. static void jobqueue_push(jobqueue* jobqueue_p, struct job* newjob){
  330. pthread_mutex_lock(&jobqueue_p->rwmutex);
  331. newjob->prev = NULL;
  332. switch(jobqueue_p->len){
  333. case 0: /* if no jobs in queue */
  334. jobqueue_p->front = newjob;
  335. jobqueue_p->rear = newjob;
  336. break;
  337. default: /* if jobs in queue */
  338. jobqueue_p->rear->prev = newjob;
  339. jobqueue_p->rear = newjob;
  340. }
  341. jobqueue_p->len++;
  342. bsem_post(jobqueue_p->has_jobs);
  343. pthread_mutex_unlock(&jobqueue_p->rwmutex);
  344. }
  345. /* Get first job from queue(removes it from queue)
  346. * Notice: Caller MUST hold a mutex
  347. */
  348. static struct job* jobqueue_pull(jobqueue* jobqueue_p){
  349. pthread_mutex_lock(&jobqueue_p->rwmutex);
  350. job* job_p = jobqueue_p->front;
  351. switch(jobqueue_p->len){
  352. case 0: /* if no jobs in queue */
  353. break;
  354. case 1: /* if one job in queue */
  355. jobqueue_p->front = NULL;
  356. jobqueue_p->rear = NULL;
  357. jobqueue_p->len = 0;
  358. break;
  359. default: /* if >1 jobs in queue */
  360. jobqueue_p->front = job_p->prev;
  361. jobqueue_p->len--;
  362. /* more than one job in queue -> post it */
  363. bsem_post(jobqueue_p->has_jobs);
  364. }
  365. pthread_mutex_unlock(&jobqueue_p->rwmutex);
  366. return job_p;
  367. }
  368. /* Free all queue resources back to the system */
  369. static void jobqueue_destroy(jobqueue* jobqueue_p){
  370. jobqueue_clear(jobqueue_p);
  371. free(jobqueue_p->has_jobs);
  372. }
  373. /* ======================== SYNCHRONISATION ========================= */
  374. /* Init semaphore to 1 or 0 */
  375. static void bsem_init(bsem *bsem_p, int value) {
  376. if (value < 0 || value > 1) {
  377. err("bsem_init(): Binary semaphore can take only values 1 or 0");
  378. exit(1);
  379. }
  380. pthread_mutex_init(&(bsem_p->mutex), NULL);
  381. pthread_cond_init(&(bsem_p->cond), NULL);
  382. bsem_p->v = value;
  383. }
  384. /* Reset semaphore to 0 */
  385. static void bsem_reset(bsem *bsem_p) {
  386. bsem_init(bsem_p, 0);
  387. }
  388. /* Post to at least one thread */
  389. static void bsem_post(bsem *bsem_p) {
  390. pthread_mutex_lock(&bsem_p->mutex);
  391. bsem_p->v = 1;
  392. pthread_cond_signal(&bsem_p->cond);
  393. pthread_mutex_unlock(&bsem_p->mutex);
  394. }
  395. /* Post to all threads */
  396. static void bsem_post_all(bsem *bsem_p) {
  397. pthread_mutex_lock(&bsem_p->mutex);
  398. bsem_p->v = 1;
  399. pthread_cond_broadcast(&bsem_p->cond);
  400. pthread_mutex_unlock(&bsem_p->mutex);
  401. }
  402. /* Wait on semaphore until semaphore has value 0 */
  403. static void bsem_wait(bsem* bsem_p) {
  404. pthread_mutex_lock(&bsem_p->mutex);
  405. while (bsem_p->v != 1) {
  406. pthread_cond_wait(&bsem_p->cond, &bsem_p->mutex);
  407. }
  408. bsem_p->v = 0;
  409. pthread_mutex_unlock(&bsem_p->mutex);
  410. }