event.d 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /**
  2. * The event module provides a primitive for lightweight signaling of other threads
  3. * (emulating Windows events on Posix)
  4. *
  5. * Copyright: Copyright (c) 2019 D Language Foundation
  6. * License: Distributed under the
  7. * $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
  8. * (See accompanying file LICENSE)
  9. * Authors: Rainer Schuetze
  10. * Source: $(DRUNTIMESRC core/sync/event.d)
  11. */
  12. module core.sync.event;
  13. version (Windows)
  14. {
  15. import core.sys.windows.basetsd /+: HANDLE +/;
  16. import core.sys.windows.winerror /+: WAIT_TIMEOUT +/;
  17. import core.sys.windows.winbase /+: CreateEvent, CloseHandle, SetEvent, ResetEvent,
  18. WaitForSingleObject, INFINITE, WAIT_OBJECT_0+/;
  19. }
  20. else version (Posix)
  21. {
  22. import core.sys.posix.pthread;
  23. import core.sys.posix.sys.types;
  24. import core.sys.posix.time;
  25. }
  26. else
  27. {
  28. static assert(false, "Platform not supported");
  29. }
  30. import core.time;
  31. import core.internal.abort : abort;
  32. /**
  33. * represents an event. Clients of an event are suspended while waiting
  34. * for the event to be "signaled".
  35. *
  36. * Implemented using `pthread_mutex` and `pthread_condition` on Posix and
  37. * `CreateEvent` and `SetEvent` on Windows.
  38. ---
  39. import core.sync.event, core.thread, std.file;
  40. struct ProcessFile
  41. {
  42. ThreadGroup group;
  43. Event event;
  44. void[] buffer;
  45. void doProcess()
  46. {
  47. event.wait();
  48. // process buffer
  49. }
  50. void process(string filename)
  51. {
  52. event.initialize(true, false);
  53. group = new ThreadGroup;
  54. for (int i = 0; i < 10; ++i)
  55. group.create(&doProcess);
  56. buffer = std.file.read(filename);
  57. event.set();
  58. group.joinAll();
  59. event.terminate();
  60. }
  61. }
  62. ---
  63. */
  64. struct Event
  65. {
  66. nothrow @nogc:
  67. /**
  68. * Creates an event object.
  69. *
  70. * Params:
  71. * manualReset = the state of the event is not reset automatically after resuming waiting clients
  72. * initialState = initial state of the signal
  73. */
  74. this(bool manualReset, bool initialState)
  75. {
  76. initialize(manualReset, initialState);
  77. }
  78. /**
  79. * Initializes an event object. Does nothing if the event is already initialized.
  80. *
  81. * Params:
  82. * manualReset = the state of the event is not reset automatically after resuming waiting clients
  83. * initialState = initial state of the signal
  84. */
  85. void initialize(bool manualReset, bool initialState)
  86. {
  87. version (Windows)
  88. {
  89. if (m_event)
  90. return;
  91. m_event = CreateEvent(null, manualReset, initialState, null);
  92. m_event || abort("Error: CreateEvent failed.");
  93. }
  94. else version (Posix)
  95. {
  96. if (m_initalized)
  97. return;
  98. pthread_mutex_init(cast(pthread_mutex_t*) &m_mutex, null) == 0 ||
  99. abort("Error: pthread_mutex_init failed.");
  100. static if ( is( typeof( pthread_condattr_setclock ) ) )
  101. {
  102. pthread_condattr_t attr = void;
  103. pthread_condattr_init(&attr) == 0 ||
  104. abort("Error: pthread_condattr_init failed.");
  105. pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) == 0 ||
  106. abort("Error: pthread_condattr_setclock failed.");
  107. pthread_cond_init(&m_cond, &attr) == 0 ||
  108. abort("Error: pthread_cond_init failed.");
  109. pthread_condattr_destroy(&attr) == 0 ||
  110. abort("Error: pthread_condattr_destroy failed.");
  111. }
  112. else
  113. {
  114. pthread_cond_init(&m_cond, null) == 0 ||
  115. abort("Error: pthread_cond_init failed.");
  116. }
  117. m_state = initialState;
  118. m_manualReset = manualReset;
  119. m_initalized = true;
  120. }
  121. }
  122. // copying not allowed, can produce resource leaks
  123. @disable this(this);
  124. @disable void opAssign(Event);
  125. ~this()
  126. {
  127. terminate();
  128. }
  129. /**
  130. * deinitialize event. Does nothing if the event is not initialized. There must not be
  131. * threads currently waiting for the event to be signaled.
  132. */
  133. void terminate()
  134. {
  135. version (Windows)
  136. {
  137. if (m_event)
  138. CloseHandle(m_event);
  139. m_event = null;
  140. }
  141. else version (Posix)
  142. {
  143. if (m_initalized)
  144. {
  145. pthread_mutex_destroy(&m_mutex) == 0 ||
  146. abort("Error: pthread_mutex_destroy failed.");
  147. pthread_cond_destroy(&m_cond) == 0 ||
  148. abort("Error: pthread_cond_destroy failed.");
  149. m_initalized = false;
  150. }
  151. }
  152. }
  153. /// Set the event to "signaled", so that waiting clients are resumed
  154. void set()
  155. {
  156. version (Windows)
  157. {
  158. if (m_event)
  159. SetEvent(m_event);
  160. }
  161. else version (Posix)
  162. {
  163. if (m_initalized)
  164. {
  165. pthread_mutex_lock(&m_mutex);
  166. m_state = true;
  167. pthread_cond_broadcast(&m_cond);
  168. pthread_mutex_unlock(&m_mutex);
  169. }
  170. }
  171. }
  172. /// Reset the event manually
  173. void reset()
  174. {
  175. version (Windows)
  176. {
  177. if (m_event)
  178. ResetEvent(m_event);
  179. }
  180. else version (Posix)
  181. {
  182. if (m_initalized)
  183. {
  184. pthread_mutex_lock(&m_mutex);
  185. m_state = false;
  186. pthread_mutex_unlock(&m_mutex);
  187. }
  188. }
  189. }
  190. /**
  191. * Wait for the event to be signaled without timeout.
  192. *
  193. * Returns:
  194. * `true` if the event is in signaled state, `false` if the event is uninitialized or another error occured
  195. */
  196. bool wait()
  197. {
  198. version (Windows)
  199. {
  200. return m_event && WaitForSingleObject(m_event, INFINITE) == WAIT_OBJECT_0;
  201. }
  202. else version (Posix)
  203. {
  204. return wait(Duration.max);
  205. }
  206. }
  207. /**
  208. * Wait for the event to be signaled with timeout.
  209. *
  210. * Params:
  211. * tmout = the maximum time to wait
  212. * Returns:
  213. * `true` if the event is in signaled state, `false` if the event was nonsignaled for the given time or
  214. * the event is uninitialized or another error occured
  215. */
  216. bool wait(Duration tmout)
  217. {
  218. version (Windows)
  219. {
  220. if (!m_event)
  221. return false;
  222. auto maxWaitMillis = dur!("msecs")(uint.max - 1);
  223. while (tmout > maxWaitMillis)
  224. {
  225. auto res = WaitForSingleObject(m_event, uint.max - 1);
  226. if (res != WAIT_TIMEOUT)
  227. return res == WAIT_OBJECT_0;
  228. tmout -= maxWaitMillis;
  229. }
  230. auto ms = cast(uint)(tmout.total!"msecs");
  231. return WaitForSingleObject(m_event, ms) == WAIT_OBJECT_0;
  232. }
  233. else version (Posix)
  234. {
  235. if (!m_initalized)
  236. return false;
  237. pthread_mutex_lock(&m_mutex);
  238. int result = 0;
  239. if (!m_state)
  240. {
  241. if (tmout == Duration.max)
  242. {
  243. result = pthread_cond_wait(&m_cond, &m_mutex);
  244. }
  245. else
  246. {
  247. import core.sync.config;
  248. timespec t = void;
  249. mktspec(t, tmout);
  250. result = pthread_cond_timedwait(&m_cond, &m_mutex, &t);
  251. }
  252. }
  253. if (result == 0 && !m_manualReset)
  254. m_state = false;
  255. pthread_mutex_unlock(&m_mutex);
  256. return result == 0;
  257. }
  258. }
  259. private:
  260. version (Windows)
  261. {
  262. HANDLE m_event;
  263. }
  264. else version (Posix)
  265. {
  266. pthread_mutex_t m_mutex;
  267. pthread_cond_t m_cond;
  268. bool m_initalized;
  269. bool m_state;
  270. bool m_manualReset;
  271. }
  272. }
  273. // Test single-thread (non-shared) use.
  274. @nogc nothrow unittest
  275. {
  276. // auto-reset, initial state false
  277. Event ev1 = Event(false, false);
  278. assert(!ev1.wait(1.dur!"msecs"));
  279. ev1.set();
  280. assert(ev1.wait());
  281. assert(!ev1.wait(1.dur!"msecs"));
  282. // manual-reset, initial state true
  283. Event ev2 = Event(true, true);
  284. assert(ev2.wait());
  285. assert(ev2.wait());
  286. ev2.reset();
  287. assert(!ev2.wait(1.dur!"msecs"));
  288. }
  289. unittest
  290. {
  291. import core.thread, core.atomic;
  292. scope event = new Event(true, false);
  293. int numThreads = 10;
  294. shared int numRunning = 0;
  295. void testFn()
  296. {
  297. event.wait(8.dur!"seconds"); // timeout below limit for druntime test_runner
  298. numRunning.atomicOp!"+="(1);
  299. }
  300. auto group = new ThreadGroup;
  301. for (int i = 0; i < numThreads; ++i)
  302. group.create(&testFn);
  303. auto start = MonoTime.currTime;
  304. assert(numRunning == 0);
  305. event.set();
  306. group.joinAll();
  307. assert(numRunning == numThreads);
  308. assert(MonoTime.currTime - start < 5.dur!"seconds");
  309. }