diff options
author | Luke T. Shumaker <lukeshu@lukeshu.com> | 2025-04-07 14:28:17 -0600 |
---|---|---|
committer | Luke T. Shumaker <lukeshu@lukeshu.com> | 2025-04-07 20:28:56 -0600 |
commit | a1a20d71f6d9f6b26893b0f2d641da47cd59e74e (patch) | |
tree | d6a692b3858f2c222dd8eeed371bf7ed4ec27db7 /libcr_ipc/waitgroup.c | |
parent | 4d5a8b2f99be5e04954c5067080d1725af8c0ae7 (diff) |
libcr_ipc: Add waitgrouplukeshu/waitgroup
Diffstat (limited to 'libcr_ipc/waitgroup.c')
-rw-r--r-- | libcr_ipc/waitgroup.c | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/libcr_ipc/waitgroup.c b/libcr_ipc/waitgroup.c new file mode 100644 index 0000000..e76db01 --- /dev/null +++ b/libcr_ipc/waitgroup.c @@ -0,0 +1,68 @@ +/* libcr_ipc/waitgroup.c - Go-like WaitGroups for libcr + * + * Copyright (C) 2025 Luke T. Shumaker <lukeshu@lukeshu.com> + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +#include <libcr/coroutine.h> /* for cid_t, cr_* */ + +#define IMPLEMENTATION_FOR_LIBCR_IPC_WAITGROUP_H YES +#include <libcr_ipc/waitgroup.h> + +#include "_linkedlist.h" + +struct cr_waitgroup_waiter { + cr_ipc_sll_node; + cid_t cid; +}; + +void cr_waitgroup_wait(cr_waitgroup_t *wg) { + assert(wg); + cr_assert_in_coroutine(); + + struct cr_waitgroup_waiter self = { + .cid = cr_getcid(), + }; + cr_ipc_sll_push_to_rear(&wg->waiters, &self); + if (wg->waiters.front != &self.cr_ipc_sll_node || wg->count > 0) + cr_pause_and_yield(); + assert(wg->waiters.front == &self.cr_ipc_sll_node); + + cr_ipc_sll_pop_from_front(&wg->waiters); + if (wg->waiters.front) { + assert(wg->unpausing); + cr_unpause(cr_ipc_sll_node_cast(struct cr_waitgroup_waiter, wg->waiters.front)->cid); + } else { + wg->unpausing = false; + } +} + +void cr_waitgroup_add(cr_waitgroup_t *wg, int delta) { + assert(wg); + cr_assert_in_coroutine(); + + if (delta == 0) + return; + bool saved = cr_save_and_disable_interrupts(); + wg->count += delta; + assert(wg->count >= 0); + if (wg->count == 0 && !wg->unpausing && wg->waiters.front) { + wg->unpausing = true; + cr_unpause(cr_ipc_sll_node_cast(struct cr_waitgroup_waiter, wg->waiters.front)->cid); + } + cr_restore_interrupts(saved); +} + +void cr_waitgroup_add_from_intrhandler(cr_waitgroup_t *wg, int delta) { + assert(wg); + cr_assert_in_intrhandler(); + + if (delta == 0) + return; + wg->count += delta; + assert(wg->count >= 0); + if (wg->count == 0 && !wg->unpausing && wg->waiters.front) { + wg->unpausing = true; + cr_unpause_from_intrhandler(cr_ipc_sll_node_cast(struct cr_waitgroup_waiter, wg->waiters.front)->cid); + } +} |