pool.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) 2016-2020 Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #ifndef POOL_H
  11. #define POOL_H
  12. #if defined (__cplusplus)
  13. extern "C" {
  14. #endif
  15. #include <stddef.h> /* size_t */
  16. typedef struct POOL_ctx_s POOL_ctx;
  17. /*! POOL_create() :
  18. * Create a thread pool with at most `numThreads` threads.
  19. * `numThreads` must be at least 1.
  20. * The maximum number of queued jobs before blocking is `queueSize`.
  21. * @return : POOL_ctx pointer on success, else NULL.
  22. */
  23. POOL_ctx* POOL_create(size_t numThreads, size_t queueSize);
  24. /*! POOL_free() :
  25. * Free a thread pool returned by POOL_create().
  26. */
  27. void POOL_free(POOL_ctx* ctx);
  28. /*! POOL_resize() :
  29. * Expands or shrinks pool's number of threads.
  30. * This is more efficient than releasing + creating a new context,
  31. * since it tries to preserve and re-use existing threads.
  32. * `numThreads` must be at least 1.
  33. * @return : 0 when resize was successful,
  34. * !0 (typically 1) if there is an error.
  35. * note : only numThreads can be resized, queueSize remains unchanged.
  36. */
  37. int POOL_resize(POOL_ctx* ctx, size_t numThreads);
  38. /*! POOL_sizeof() :
  39. * @return threadpool memory usage
  40. * note : compatible with NULL (returns 0 in this case)
  41. */
  42. size_t POOL_sizeof(POOL_ctx* ctx);
  43. /*! POOL_function :
  44. * The function type that can be added to a thread pool.
  45. */
  46. typedef void (*POOL_function)(void*);
  47. /*! POOL_add() :
  48. * Add the job `function(opaque)` to the thread pool. `ctx` must be valid.
  49. * Possibly blocks until there is room in the queue.
  50. * Note : The function may be executed asynchronously,
  51. * therefore, `opaque` must live until function has been completed.
  52. */
  53. void POOL_add(POOL_ctx* ctx, POOL_function function, void* opaque);
  54. /*! POOL_tryAdd() :
  55. * Add the job `function(opaque)` to thread pool _if_ a worker is available.
  56. * Returns immediately even if not (does not block).
  57. * @return : 1 if successful, 0 if not.
  58. */
  59. int POOL_tryAdd(POOL_ctx* ctx, POOL_function function, void* opaque);
  60. #if defined (__cplusplus)
  61. }
  62. #endif
  63. #endif