extended.odin 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. package sync
  2. import "core:time"
  3. import vg "core:sys/valgrind"
  4. _ :: vg
  5. /*
  6. Wait group.
  7. Wait group is a synchronization primitive used by the waiting thread to wait,
  8. until a all working threads finish work.
  9. The waiting thread first sets the number of working threads it will expect to
  10. wait for using `wait_group_add` call, and start waiting using `wait_group_wait`
  11. call. When worker threads complete their work, each of them will call
  12. `wait_group_done`, and after all working threads have called this procedure,
  13. the waiting thread will resume execution.
  14. For the purpose of keeping track whether all working threads have finished their
  15. work, the wait group keeps an internal atomic counter. Initially, the waiting
  16. thread might set it to a certain non-zero amount. When each working thread
  17. completes the work, the internal counter is atomically decremented until it
  18. reaches zero. When it reaches zero, the waiting thread is unblocked. The counter
  19. is not allowed to become negative.
  20. **Note**: Just like any synchronization primitives, a wait group cannot be
  21. copied after first use. See documentation for `Mutex` or `Cond`.
  22. */
  23. Wait_Group :: struct #no_copy {
  24. counter: int,
  25. mutex: Mutex,
  26. cond: Cond,
  27. }
  28. /*
  29. Increment an internal counter of a wait group.
  30. This procedure atomicaly increments a number to the specified wait group's
  31. internal counter by a specified amount. This operation can be done on any
  32. thread.
  33. */
  34. wait_group_add :: proc "contextless" (wg: ^Wait_Group, delta: int) {
  35. if delta == 0 {
  36. return
  37. }
  38. guard(&wg.mutex)
  39. atomic_add(&wg.counter, delta)
  40. if wg.counter < 0 {
  41. _panic("sync.Wait_Group negative counter")
  42. }
  43. if wg.counter == 0 {
  44. cond_broadcast(&wg.cond)
  45. if wg.counter != 0 {
  46. _panic("sync.Wait_Group misuse: sync.wait_group_add called concurrently with sync.wait_group_wait")
  47. }
  48. }
  49. }
  50. /*
  51. Signal work done by a thread in a wait group.
  52. This procedure decrements the internal counter of the specified wait group and
  53. wakes up the waiting thread. Once the internal counter reaches zero, the waiting
  54. thread resumes execution.
  55. */
  56. wait_group_done :: proc "contextless" (wg: ^Wait_Group) {
  57. wait_group_add(wg, -1)
  58. }
  59. /*
  60. Wait for all worker threads in the wait group.
  61. This procedure blocks the execution of the current thread, until the specified
  62. wait group's internal counter reaches zero.
  63. */
  64. wait_group_wait :: proc "contextless" (wg: ^Wait_Group) {
  65. guard(&wg.mutex)
  66. if wg.counter != 0 {
  67. cond_wait(&wg.cond, &wg.mutex)
  68. if wg.counter != 0 {
  69. _panic("sync.Wait_Group misuse: sync.wait_group_add called concurrently with sync.wait_group_wait")
  70. }
  71. }
  72. }
  73. /*
  74. Wait for all worker threads in the wait group, or until timeout is reached.
  75. This procedure blocks the execution of the current thread, until the specified
  76. wait group's internal counter reaches zero, or until the timeout is reached.
  77. This procedure returns `false`, if the timeout was reached, `true` otherwise.
  78. */
  79. wait_group_wait_with_timeout :: proc "contextless" (wg: ^Wait_Group, duration: time.Duration) -> bool {
  80. if duration <= 0 {
  81. return false
  82. }
  83. guard(&wg.mutex)
  84. if wg.counter != 0 {
  85. if !cond_wait_with_timeout(&wg.cond, &wg.mutex, duration) {
  86. return false
  87. }
  88. if wg.counter != 0 {
  89. _panic("sync.Wait_Group misuse: sync.wait_group_add called concurrently with sync.wait_group_wait")
  90. }
  91. }
  92. return true
  93. }
  94. /*
  95. Barrier.
  96. A barrier is a synchronization primitive enabling multiple threads to
  97. synchronize the beginning of some computation.
  98. When `barrier_wait` procedure is called by any thread, that thread will block
  99. the execution, until all threads associated with the barrier reach the same
  100. point of execution and also call `barrier_wait`.
  101. when barrier is initialized, a `thread_count` parameter is passed, signifying
  102. the amount of participant threads of the barrier. The barrier also keeps track
  103. of an internal atomic counter. When a thread calls `barrier_wait`, the internal
  104. counter is incremented. When the internal counter reaches `thread_count`, it is
  105. reset and all threads waiting on the barrier are unblocked.
  106. This type of synchronization primitive can be used to synchronize "staged"
  107. workloads, where the workload is split into stages, and until all threads have
  108. completed the previous threads, no thread is allowed to start work on the next
  109. stage. In this case, after each stage, a `barrier_wait` shall be inserted in the
  110. thread procedure.
  111. **Example**:
  112. THREAD_COUNT :: 4
  113. threads: [THREAD_COUNT]^thread.Thread
  114. sync.barrier_init(barrier, THREAD_COUNT)
  115. for _, i in threads {
  116. threads[i] = thread.create_and_start(proc(t: ^thread.Thread) {
  117. // Same messages will be printed together but without any interleaving
  118. fmt.println("Getting ready!")
  119. sync.barrier_wait(barrier)
  120. fmt.println("Off their marks they go!")
  121. })
  122. }
  123. for t in threads {
  124. thread.destroy(t)
  125. }
  126. */
  127. Barrier :: struct #no_copy {
  128. mutex: Mutex,
  129. cond: Cond,
  130. index: int,
  131. generation_id: int,
  132. thread_count: int,
  133. }
  134. /*
  135. Initialize a barrier.
  136. This procedure initializes the barrier for the specified amount of participant
  137. threads.
  138. */
  139. barrier_init :: proc "contextless" (b: ^Barrier, thread_count: int) {
  140. when ODIN_VALGRIND_SUPPORT {
  141. vg.helgrind_barrier_resize_pre(b, uint(thread_count))
  142. }
  143. b.index = 0
  144. b.generation_id = 0
  145. b.thread_count = thread_count
  146. }
  147. /*
  148. Block the current thread until all threads have rendezvoused.
  149. This procedure blocks the execution of the current thread, until all threads
  150. have reached the same point in the execution of the thread proc. Multiple calls
  151. to `barrier_wait` are allowed within the thread procedure.
  152. */
  153. barrier_wait :: proc "contextless" (b: ^Barrier) -> (is_leader: bool) {
  154. when ODIN_VALGRIND_SUPPORT {
  155. vg.helgrind_barrier_wait_pre(b)
  156. }
  157. guard(&b.mutex)
  158. local_gen := b.generation_id
  159. b.index += 1
  160. if b.index < b.thread_count {
  161. for local_gen == b.generation_id && b.index < b.thread_count {
  162. cond_wait(&b.cond, &b.mutex)
  163. }
  164. return false
  165. }
  166. b.index = 0
  167. b.generation_id += 1
  168. cond_broadcast(&b.cond)
  169. return true
  170. }
  171. /*
  172. Auto-reset event.
  173. Represents a thread synchronization primitive that, when signalled, releases one
  174. single waiting thread and then resets automatically to a state where it can be
  175. signalled again.
  176. When a thread calls `auto_reset_event_wait`, it's execution will be blocked,
  177. until the event is signalled by another thread. The call to
  178. `auto_reset_event_signal` wakes up exactly one thread waiting for the event.
  179. */
  180. Auto_Reset_Event :: struct #no_copy {
  181. // status == 0: Event is reset and no threads are waiting
  182. // status == 1: Event is signalled
  183. // status == -N: Event is reset and N threads are waiting
  184. status: i32,
  185. sema: Sema,
  186. }
  187. /*
  188. Signal an auto-reset event.
  189. This procedure signals an auto-reset event, waking up exactly one waiting
  190. thread.
  191. */
  192. auto_reset_event_signal :: proc "contextless" (e: ^Auto_Reset_Event) {
  193. old_status := atomic_load_explicit(&e.status, .Relaxed)
  194. for {
  195. new_status := old_status + 1 if old_status < 1 else 1
  196. if _, ok := atomic_compare_exchange_weak_explicit(&e.status, old_status, new_status, .Release, .Relaxed); ok {
  197. break
  198. }
  199. if old_status < 0 {
  200. sema_post(&e.sema)
  201. }
  202. }
  203. }
  204. /*
  205. Wait on an auto-reset event.
  206. This procedure blocks the execution of the current thread, until the event is
  207. signalled by another thread.
  208. */
  209. auto_reset_event_wait :: proc "contextless" (e: ^Auto_Reset_Event) {
  210. old_status := atomic_sub_explicit(&e.status, 1, .Acquire)
  211. if old_status < 1 {
  212. sema_wait(&e.sema)
  213. }
  214. }
  215. /*
  216. Ticket lock.
  217. A ticket lock is a mutual exclusion lock that uses "tickets" to control which
  218. thread is allowed into a critical section.
  219. This synchronization primitive works just like spinlock, except that it implements
  220. a "fairness" guarantee, making sure that each thread gets a roughly equal amount
  221. of entries into the critical section.
  222. This type of synchronization primitive is applicable for short critical sections
  223. in low-contention systems, as it uses a spinlock under the hood.
  224. */
  225. Ticket_Mutex :: struct #no_copy {
  226. ticket: uint,
  227. serving: uint,
  228. }
  229. /*
  230. Acquire a lock on a ticket mutex.
  231. This procedure acquires a lock on a ticket mutex. If the ticket mutex is held
  232. by another thread, this procedure also blocks the execution until the lock
  233. can be acquired.
  234. Once the lock is acquired, any thread calling `ticket_mutex_lock` will be
  235. blocked from entering any critical sections associated with the same ticket
  236. mutex, until the lock is released.
  237. */
  238. ticket_mutex_lock :: #force_inline proc "contextless" (m: ^Ticket_Mutex) {
  239. ticket := atomic_add_explicit(&m.ticket, 1, .Relaxed)
  240. for ticket != atomic_load_explicit(&m.serving, .Acquire) {
  241. cpu_relax()
  242. }
  243. }
  244. /*
  245. Release a lock on a ticket mutex.
  246. This procedure releases the lock on a ticket mutex. If any of the threads are
  247. waiting to acquire the lock, exactly one of those threads is unblocked and
  248. allowed into the critical section.
  249. */
  250. ticket_mutex_unlock :: #force_inline proc "contextless" (m: ^Ticket_Mutex) {
  251. atomic_add_explicit(&m.serving, 1, .Relaxed)
  252. }
  253. /*
  254. Guard the current scope with a lock on a ticket mutex.
  255. This procedure acquires a lock on a ticket mutex. The lock is automatically
  256. released at the end of callee's scope. If the mutex was already locked, this
  257. procedure also blocks until the lock can be acquired.
  258. When a lock has been acquired, all threads attempting to acquire a lock will be
  259. blocked from entering any critical sections associated with the ticket mutex,
  260. until the lock is released.
  261. This procedure always returns `true`. This makes it easy to define a critical
  262. section by putting the function inside the `if` statement.
  263. **Example**:
  264. if ticket_mutex_guard(&m) {
  265. ...
  266. }
  267. */
  268. @(deferred_in=ticket_mutex_unlock)
  269. ticket_mutex_guard :: proc "contextless" (m: ^Ticket_Mutex) -> bool {
  270. ticket_mutex_lock(m)
  271. return true
  272. }
  273. /*
  274. Benaphore.
  275. A benaphore is a combination of an atomic variable and a semaphore that can
  276. improve locking efficiency in a no-contention system. Acquiring a benaphore
  277. lock doesn't call into an internal semaphore, if no other thread in a middle of
  278. a critical section.
  279. Once a lock on a benaphore is acquired by a thread, no other thread is allowed
  280. into any critical sections, associted with the same benaphore, until the lock
  281. is released.
  282. */
  283. Benaphore :: struct #no_copy {
  284. counter: i32,
  285. sema: Sema,
  286. }
  287. /*
  288. Acquire a lock on a benaphore.
  289. This procedure acquires a lock on the specified benaphore. If the lock on a
  290. benaphore is already held, this procedure also blocks the execution of the
  291. current thread, until the lock could be acquired.
  292. Once a lock is acquired, all threads attempting to take a lock will be blocked
  293. from entering any critical sections associated with the same benaphore, until
  294. until the lock is released.
  295. */
  296. benaphore_lock :: proc "contextless" (b: ^Benaphore) {
  297. if atomic_add_explicit(&b.counter, 1, .Acquire) > 1 {
  298. sema_wait(&b.sema)
  299. }
  300. }
  301. /*
  302. Try to acquire a lock on a benaphore.
  303. This procedure tries to acquire a lock on the specified benaphore. If it was
  304. already locked, then the returned value is `false`, otherwise the lock is
  305. acquired and the procedure returns `true`.
  306. If the lock is acquired, all threads that attempt to acquire a lock will be
  307. blocked from entering any critical sections associated with the same benaphore,
  308. until the lock is released.
  309. */
  310. benaphore_try_lock :: proc "contextless" (b: ^Benaphore) -> bool {
  311. v, _ := atomic_compare_exchange_strong_explicit(&b.counter, 0, 1, .Acquire, .Acquire)
  312. return v == 0
  313. }
  314. /*
  315. Release a lock on a benaphore.
  316. This procedure releases a lock on the specified benaphore. If any of the threads
  317. are waiting on the lock, exactly one thread is allowed into a critical section
  318. associated with the same banaphore.
  319. */
  320. benaphore_unlock :: proc "contextless" (b: ^Benaphore) {
  321. if atomic_sub_explicit(&b.counter, 1, .Release) > 0 {
  322. sema_post(&b.sema)
  323. }
  324. }
  325. /*
  326. Guard the current scope with a lock on a benaphore.
  327. This procedure acquires a lock on a benaphore. The lock is automatically
  328. released at the end of callee's scope. If the benaphore was already locked, this
  329. procedure also blocks until the lock can be acquired.
  330. When a lock has been acquired, all threads attempting to acquire a lock will be
  331. blocked from entering any critical sections associated with the same benaphore,
  332. until the lock is released.
  333. This procedure always returns `true`. This makes it easy to define a critical
  334. section by putting the function inside the `if` statement.
  335. **Example**:
  336. if benaphore_guard(&m) {
  337. ...
  338. }
  339. */
  340. @(deferred_in=benaphore_unlock)
  341. benaphore_guard :: proc "contextless" (m: ^Benaphore) -> bool {
  342. benaphore_lock(m)
  343. return true
  344. }
  345. /*
  346. Recursive benaphore.
  347. Recurisve benaphore is just like a plain benaphore, except it allows reentrancy
  348. into the critical section.
  349. When a lock is acquired on a benaphore, all other threads attempting to
  350. acquire a lock on the same benaphore will be blocked from any critical sections,
  351. associated with the same benaphore.
  352. When a lock is acquired on a benaphore by a thread, that thread is allowed
  353. to acquire another lock on the same benaphore. When a thread has acquired the
  354. lock on a benaphore, the benaphore will stay locked until the thread releases
  355. the lock as many times as it has been locked by the thread.
  356. */
  357. Recursive_Benaphore :: struct #no_copy {
  358. counter: int,
  359. owner: int,
  360. recursion: i32,
  361. sema: Sema,
  362. }
  363. /*
  364. Acquire a lock on a recursive benaphore.
  365. This procedure acquires a lock on a recursive benaphore. If the benaphore is
  366. held by another thread, this function blocks until the lock can be acquired.
  367. Once a lock is acquired, all other threads attempting to acquire a lock will
  368. be blocked from entering any critical sections associated with the same
  369. recursive benaphore, until the lock is released.
  370. */
  371. recursive_benaphore_lock :: proc "contextless" (b: ^Recursive_Benaphore) {
  372. tid := current_thread_id()
  373. if atomic_add_explicit(&b.counter, 1, .Acquire) > 1 {
  374. if tid != b.owner {
  375. sema_wait(&b.sema)
  376. }
  377. }
  378. // inside the lock
  379. b.owner = tid
  380. b.recursion += 1
  381. }
  382. /*
  383. Try to acquire a lock on a recursive benaphore.
  384. This procedure attempts to acquire a lock on recursive benaphore. If the
  385. benaphore is already held by a different thread, this procedure returns `false`.
  386. Otherwise the lock is acquired and the procedure returns `true`.
  387. If the lock is acquired, all other threads attempting to acquire a lock will
  388. be blocked from entering any critical sections assciated with the same recursive
  389. benaphore, until the lock is released.
  390. */
  391. recursive_benaphore_try_lock :: proc "contextless" (b: ^Recursive_Benaphore) -> bool {
  392. tid := current_thread_id()
  393. if b.owner == tid {
  394. atomic_add_explicit(&b.counter, 1, .Acquire)
  395. }
  396. if v, _ := atomic_compare_exchange_strong_explicit(&b.counter, 0, 1, .Acquire, .Acquire); v != 0 {
  397. return false
  398. }
  399. // inside the lock
  400. b.owner = tid
  401. b.recursion += 1
  402. return true
  403. }
  404. /*
  405. Release a lock on a recursive benaphore.
  406. This procedure releases a lock on the specified recursive benaphore. It also
  407. causes the critical sections associated with the same benaphore, to become open
  408. for other threads for entering.
  409. */
  410. recursive_benaphore_unlock :: proc "contextless" (b: ^Recursive_Benaphore) {
  411. tid := current_thread_id()
  412. _assert(tid == b.owner, "tid != b.owner")
  413. b.recursion -= 1
  414. recursion := b.recursion
  415. if recursion == 0 {
  416. b.owner = 0
  417. }
  418. if atomic_sub_explicit(&b.counter, 1, .Release) > 0 {
  419. if recursion == 0 {
  420. sema_post(&b.sema)
  421. }
  422. }
  423. // outside the lock
  424. }
  425. /*
  426. Guard the current scope with a recursive benaphore.
  427. This procedure acquires a lock on the specified recursive benaphores and
  428. automatically releases it at the end of the callee's scope. If the recursive
  429. benaphore was already held by a another thread, this procedure also blocks until
  430. the lock can be acquired.
  431. When the lock is acquired all other threads attempting to take a lock will be
  432. blocked from entering any critical sections associated with the same benaphore,
  433. until the lock is released.
  434. This procedure always returns `true`, which makes it easy to define a critical
  435. section by calling this procedure inside an `if` statement.
  436. **Example**:
  437. if recursive_benaphore_guard(&m) {
  438. ...
  439. }
  440. */
  441. @(deferred_in=recursive_benaphore_unlock)
  442. recursive_benaphore_guard :: proc "contextless" (m: ^Recursive_Benaphore) -> bool {
  443. recursive_benaphore_lock(m)
  444. return true
  445. }
  446. /*
  447. Once action.
  448. `Once` a synchronization primitive, that only allows a single entry into a
  449. critical section from a single thread.
  450. */
  451. Once :: struct #no_copy {
  452. m: Mutex,
  453. done: bool,
  454. }
  455. /*
  456. Call a function once.
  457. The `once_do` procedure group calls a specified function, if it wasn't already
  458. called from the perspective of a specific `Once` struct.
  459. */
  460. once_do :: proc{
  461. once_do_without_data,
  462. once_do_without_data_contextless,
  463. once_do_with_data,
  464. once_do_with_data_contextless,
  465. }
  466. /*
  467. Call a function with no data once.
  468. */
  469. once_do_without_data :: proc(o: ^Once, fn: proc()) {
  470. @(cold)
  471. do_slow :: proc(o: ^Once, fn: proc()) {
  472. guard(&o.m)
  473. if !o.done {
  474. fn()
  475. atomic_store_explicit(&o.done, true, .Release)
  476. }
  477. }
  478. if atomic_load_explicit(&o.done, .Acquire) == false {
  479. do_slow(o, fn)
  480. }
  481. }
  482. /*
  483. Call a contextless function with no data once.
  484. */
  485. once_do_without_data_contextless :: proc(o: ^Once, fn: proc "contextless" ()) {
  486. @(cold)
  487. do_slow :: proc(o: ^Once, fn: proc "contextless" ()) {
  488. guard(&o.m)
  489. if !o.done {
  490. fn()
  491. atomic_store_explicit(&o.done, true, .Release)
  492. }
  493. }
  494. if atomic_load_explicit(&o.done, .Acquire) == false {
  495. do_slow(o, fn)
  496. }
  497. }
  498. /*
  499. Call a function with data once.
  500. */
  501. once_do_with_data :: proc(o: ^Once, fn: proc(data: rawptr), data: rawptr) {
  502. @(cold)
  503. do_slow :: proc(o: ^Once, fn: proc(data: rawptr), data: rawptr) {
  504. guard(&o.m)
  505. if !o.done {
  506. fn(data)
  507. atomic_store_explicit(&o.done, true, .Release)
  508. }
  509. }
  510. if atomic_load_explicit(&o.done, .Acquire) == false {
  511. do_slow(o, fn, data)
  512. }
  513. }
  514. /*
  515. Call a contextless function with data once.
  516. */
  517. once_do_with_data_contextless :: proc "contextless" (o: ^Once, fn: proc "contextless" (data: rawptr), data: rawptr) {
  518. @(cold)
  519. do_slow :: proc "contextless" (o: ^Once, fn: proc "contextless" (data: rawptr), data: rawptr) {
  520. guard(&o.m)
  521. if !o.done {
  522. fn(data)
  523. atomic_store_explicit(&o.done, true, .Release)
  524. }
  525. }
  526. if atomic_load_explicit(&o.done, .Acquire) == false {
  527. do_slow(o, fn, data)
  528. }
  529. }
  530. /*
  531. A Parker is an associated token which is initially not present:
  532. * The `park` procedure blocks the current thread unless or until the token
  533. is available, at which point the token is consumed.
  534. * The `park_with_timeout` procedures works the same as `park` but only
  535. blocks for the specified duration.
  536. * The `unpark` procedure automatically makes the token available if it
  537. was not already.
  538. */
  539. Parker :: struct #no_copy {
  540. state: Futex,
  541. }
  542. @(private="file") PARKER_EMPTY :: 0
  543. @(private="file") PARKER_NOTIFIED :: 1
  544. @(private="file") PARKER_PARKED :: max(u32)
  545. /*
  546. Blocks until the token is available.
  547. This procedure blocks the execution of the current thread, until a token is
  548. made available.
  549. **Note**: This procedure assumes this is only called by the thread that owns
  550. the Parker.
  551. */
  552. park :: proc "contextless" (p: ^Parker) {
  553. if atomic_sub_explicit(&p.state, 1, .Acquire) == PARKER_NOTIFIED {
  554. return
  555. }
  556. for {
  557. futex_wait(&p.state, PARKER_PARKED)
  558. if _, ok := atomic_compare_exchange_strong_explicit(&p.state, PARKER_NOTIFIED, PARKER_EMPTY, .Acquire, .Acquire); ok {
  559. return
  560. }
  561. }
  562. }
  563. /*
  564. Blocks until the token is available with timeout.
  565. This procedure blocks the execution of the current thread until a token is made
  566. available, or until the timeout has expired, whatever happens first.
  567. **Note**: This procedure assumes this is only called by the thread that owns
  568. the Parker.
  569. */
  570. park_with_timeout :: proc "contextless" (p: ^Parker, duration: time.Duration) {
  571. start_tick := time.tick_now()
  572. remaining_duration := duration
  573. if atomic_sub_explicit(&p.state, 1, .Acquire) == PARKER_NOTIFIED {
  574. return
  575. }
  576. for {
  577. if !futex_wait_with_timeout(&p.state, PARKER_PARKED, remaining_duration) {
  578. return
  579. }
  580. old, ok := atomic_compare_exchange_weak_explicit((^u32)(&p.state), PARKER_PARKED, PARKER_EMPTY, .Acquire, .Relaxed)
  581. if ok || old == PARKER_PARKED {
  582. return
  583. }
  584. end_tick := time.tick_now()
  585. remaining_duration -= time.tick_diff(start_tick, end_tick)
  586. start_tick = end_tick
  587. }
  588. }
  589. /*
  590. Make the token available.
  591. */
  592. unpark :: proc "contextless" (p: ^Parker) {
  593. if atomic_exchange_explicit((^u32)(&p.state), PARKER_NOTIFIED, .Release) == PARKER_PARKED {
  594. futex_signal(&p.state)
  595. }
  596. }
  597. /*
  598. One-shot event.
  599. A one-shot event is an associated token which is initially not present:
  600. * The `one_shot_event_wait` blocks the current thread until the event
  601. is made available
  602. * The `one_shot_event_signal` procedure automatically makes the token
  603. available if its was not already.
  604. */
  605. One_Shot_Event :: struct #no_copy {
  606. state: Futex,
  607. }
  608. /*
  609. Block until the event is made available.
  610. This procedure blocks the execution of the current thread, until the event is
  611. made available.
  612. */
  613. one_shot_event_wait :: proc "contextless" (e: ^One_Shot_Event) {
  614. for atomic_load_explicit(&e.state, .Acquire) == 0 {
  615. futex_wait(&e.state, 0)
  616. }
  617. }
  618. /*
  619. Make event available.
  620. */
  621. one_shot_event_signal :: proc "contextless" (e: ^One_Shot_Event) {
  622. atomic_store_explicit(&e.state, 1, .Release)
  623. futex_broadcast(&e.state)
  624. }