extended.odin 21 KB

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