thpool.c 13 KB

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