You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.5 KiB

  1. /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
  2. // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
  3. #ident "$Id$"
  4. #ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved."
  5. #ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <toku_assert.h>
  9. #include <malloc.h>
  10. #include <pthread.h>
  11. #include <errno.h>
  12. #include "threadpool.h"
  13. #include <portability/toku_atomic.h>
  14. // use gcc builtin fetch_and_add 0->no 1->yes
  15. #define DO_ATOMIC_FETCH_AND_ADD 0
  16. struct threadpool {
  17. int max_threads;
  18. int current_threads;
  19. int busy_threads;
  20. pthread_t pids[];
  21. };
  22. int threadpool_create(THREADPOOL *threadpoolptr, int max_threads) {
  23. size_t size = sizeof (struct threadpool) + max_threads*sizeof (pthread_t);
  24. struct threadpool *threadpool = (struct threadpool *) malloc(size);
  25. if (threadpool == 0)
  26. return ENOMEM;
  27. threadpool->max_threads = max_threads;
  28. threadpool->current_threads = 0;
  29. threadpool->busy_threads = 0;
  30. int i;
  31. for (i=0; i<max_threads; i++)
  32. threadpool->pids[i] = 0;
  33. *threadpoolptr = threadpool;
  34. return 0;
  35. }
  36. void threadpool_destroy(THREADPOOL *threadpoolptr) {
  37. struct threadpool *threadpool = *threadpoolptr;
  38. int i;
  39. for (i=0; i<threadpool->current_threads; i++) {
  40. int r; void *ret;
  41. r = pthread_join(threadpool->pids[i], &ret);
  42. assert(r == 0);
  43. }
  44. *threadpoolptr = 0;
  45. free(threadpool);
  46. }
  47. void threadpool_maybe_add(THREADPOOL threadpool, void *(*f)(void *), void *arg) {
  48. if (threadpool->current_threads < threadpool->max_threads) {
  49. int r = pthread_create(&threadpool->pids[threadpool->current_threads], 0, f, arg);
  50. if (r == 0) {
  51. threadpool->current_threads++;
  52. threadpool_set_thread_busy(threadpool);
  53. }
  54. }
  55. }
  56. void threadpool_set_thread_busy(THREADPOOL threadpool) {
  57. #if DO_ATOMIC_FETCH_AND_ADD
  58. (void) toku_sync_fetch_and_add(&threadpool->busy_threads, 1);
  59. #else
  60. threadpool->busy_threads++;
  61. #endif
  62. }
  63. void threadpool_set_thread_idle(THREADPOOL threadpool) {
  64. #if DO_ATOMIC_FETCH_AND_ADD
  65. (void) toku_sync_fetch_and_add(&threadpool->busy_threads, -1);
  66. #else
  67. threadpool->busy_threads--;
  68. #endif
  69. }
  70. int threadpool_get_current_threads(THREADPOOL threadpool) {
  71. return threadpool->current_threads;
  72. }