compat_threads.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2015, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #ifndef TOR_COMPAT_THREADS_H
  6. #define TOR_COMPAT_THREADS_H
  7. #include "orconfig.h"
  8. #include "torint.h"
  9. #include "testsupport.h"
  10. #if defined(HAVE_PTHREAD_H) && !defined(_WIN32)
  11. #include <pthread.h>
  12. #endif
  13. #if defined(_WIN32)
  14. #define USE_WIN32_THREADS
  15. #elif defined(HAVE_PTHREAD_H) && defined(HAVE_PTHREAD_CREATE)
  16. #define USE_PTHREADS
  17. #else
  18. #error "No threading system was found"
  19. #endif
  20. int spawn_func(void (*func)(void *), void *data);
  21. void spawn_exit(void) ATTR_NORETURN;
  22. /* Because we use threads instead of processes on most platforms (Windows,
  23. * Linux, etc), we need locking for them. On platforms with poor thread
  24. * support or broken gethostbyname_r, these functions are no-ops. */
  25. /** A generic lock structure for multithreaded builds. */
  26. typedef struct tor_mutex_t {
  27. #if defined(USE_WIN32_THREADS)
  28. /** Windows-only: on windows, we implement locks with CRITICAL_SECTIONS. */
  29. CRITICAL_SECTION mutex;
  30. #elif defined(USE_PTHREADS)
  31. /** Pthreads-only: with pthreads, we implement locks with
  32. * pthread_mutex_t. */
  33. pthread_mutex_t mutex;
  34. #else
  35. /** No-threads only: Dummy variable so that tor_mutex_t takes up space. */
  36. int _unused;
  37. #endif
  38. } tor_mutex_t;
  39. tor_mutex_t *tor_mutex_new(void);
  40. void tor_mutex_init(tor_mutex_t *m);
  41. void tor_mutex_acquire(tor_mutex_t *m);
  42. void tor_mutex_release(tor_mutex_t *m);
  43. void tor_mutex_free(tor_mutex_t *m);
  44. void tor_mutex_uninit(tor_mutex_t *m);
  45. unsigned long tor_get_thread_id(void);
  46. void tor_threads_init(void);
  47. void set_main_thread(void);
  48. int in_main_thread(void);
  49. typedef struct tor_cond_t {
  50. #ifdef USE_PTHREADS
  51. pthread_cond_t cond;
  52. #elif defined(USE_WIN32_THREADS)
  53. HANDLE event;
  54. CRITICAL_SECTION lock;
  55. int n_waiting;
  56. int n_to_wake;
  57. int generation;
  58. #else
  59. #error no known condition implementation.
  60. #endif
  61. } tor_cond_t;
  62. tor_cond_t *tor_cond_new(void);
  63. void tor_cond_free(tor_cond_t *cond);
  64. int tor_cond_init(tor_cond_t *cond);
  65. void tor_cond_uninit(tor_cond_t *cond);
  66. int tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex,
  67. const struct timeval *tv);
  68. void tor_cond_signal_one(tor_cond_t *cond);
  69. void tor_cond_signal_all(tor_cond_t *cond);
  70. #endif