threads.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #pragma once
  2. #include "pocketpy/config.h"
  3. #if PK_ENABLE_THREADS
  4. #include <stdatomic.h>
  5. #include <stdbool.h>
  6. #if __EMSCRIPTEN__ || __APPLE__ || __linux__
  7. #include <pthread.h>
  8. #define PK_USE_PTHREADS 1
  9. typedef pthread_t c11_thrd_t;
  10. typedef void* c11_thrd_retval_t;
  11. typedef pthread_mutex_t c11_mutex_t;
  12. typedef pthread_cond_t c11_cond_t;
  13. #else
  14. #include <threads.h>
  15. #define PK_USE_PTHREADS 0
  16. typedef thrd_t c11_thrd_t;
  17. typedef int c11_thrd_retval_t;
  18. typedef mtx_t c11_mutex_t;
  19. typedef cnd_t c11_cond_t;
  20. #endif
  21. typedef c11_thrd_retval_t (*c11_thrd_func_t)(void*);
  22. bool c11_thrd__create(c11_thrd_t* thrd, c11_thrd_func_t func, void* arg);
  23. void c11_thrd__yield();
  24. void c11_thrd__join(c11_thrd_t thrd);
  25. c11_thrd_t c11_thrd__current();
  26. bool c11_thrd__equal(c11_thrd_t a, c11_thrd_t b);
  27. void c11_mutex__ctor(c11_mutex_t* mutex);
  28. void c11_mutex__dtor(c11_mutex_t* mutex);
  29. void c11_mutex__lock(c11_mutex_t* mutex);
  30. void c11_mutex__unlock(c11_mutex_t* mutex);
  31. void c11_cond__ctor(c11_cond_t* cond);
  32. void c11_cond__dtor(c11_cond_t* cond);
  33. void c11_cond__wait(c11_cond_t* cond, c11_mutex_t* mutex);
  34. void c11_cond__signal(c11_cond_t* cond);
  35. void c11_cond__broadcast(c11_cond_t* cond);
  36. typedef void (*c11_thrdpool_func_t)(void* arg);
  37. typedef struct c11_thrdpool_tasks {
  38. c11_thrdpool_func_t func;
  39. void** args;
  40. int length;
  41. int sync_val;
  42. atomic_int current_index;
  43. atomic_int completed_count;
  44. } c11_thrdpool_tasks;
  45. typedef struct c11_thrdpool_worker {
  46. c11_mutex_t* p_mutex;
  47. c11_cond_t* p_cond;
  48. c11_thrdpool_tasks* p_tasks;
  49. c11_thrd_t thread;
  50. } c11_thrdpool_worker;
  51. typedef struct c11_thrdpool {
  52. int length;
  53. c11_thrdpool_worker* workers;
  54. atomic_bool is_busy;
  55. c11_mutex_t workers_mutex[2];
  56. c11_cond_t workers_cond[2];
  57. c11_thrdpool_tasks tasks;
  58. } c11_thrdpool;
  59. void c11_thrdpool__ctor(c11_thrdpool* pool, int length);
  60. void c11_thrdpool__dtor(c11_thrdpool* pool);
  61. void c11_thrdpool__map(c11_thrdpool* pool, c11_thrdpool_func_t func, void** args, int num_tasks);
  62. #endif