From 7b4a05d535f0ecc070e9b506ad0a667e24b67f71 Mon Sep 17 00:00:00 2001 From: Harald Welte Date: Mon, 18 Mar 2019 17:17:43 +0100 Subject: context: Add support for [per-thread] global talloc contexts Rather than having applications maintain their own talloc cotexts, let's offer some root talloc contexts in libosmocore. Let's also make them per thread right from the beginning. This will help some multi-threaded applications to use talloc in a thread-safe way. Change-Id: Iae39cd57274bf6753ecaf186f229e582b42662e3 --- include/osmocom/core/select.h | 1 + include/osmocom/core/talloc.h | 28 +++++++++++++++++++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/osmocom/core/select.h b/include/osmocom/core/select.h index e4787b09..a200b6f3 100644 --- a/include/osmocom/core/select.h +++ b/include/osmocom/core/select.h @@ -51,6 +51,7 @@ int osmo_fd_register(struct osmo_fd *fd); void osmo_fd_unregister(struct osmo_fd *fd); void osmo_fd_close(struct osmo_fd *fd); int osmo_select_main(int polling); +int osmo_select_main_ctx(int polling); struct osmo_fd *osmo_fd_get_by_fd(int fd); diff --git a/include/osmocom/core/talloc.h b/include/osmocom/core/talloc.h index 191a463f..c68a56cf 100644 --- a/include/osmocom/core/talloc.h +++ b/include/osmocom/core/talloc.h @@ -1,5 +1,27 @@ -/*! \file talloc.h - * Convenience wrapper. libosmocore used to ship its own internal copy of - * talloc, before libtalloc became a standard component on most systems */ +/*! \file talloc.h */ #pragma once #include + +/*! per-thread talloc contexts. This works around the problem that talloc is not + * thread-safe. However, one can simply have a different set of talloc contexts for each + * thread, and ensure that allocations made on one thread are always only free'd on that + * very same thread. + * WARNING: Users must make sure they free() on the same thread as they allocate!! */ +struct osmo_talloc_contexts { + /*! global per-thread talloc context. */ + void *global; + /*! volatile select-dispatch context. This context is completely free'd and + * re-created every time the main select loop in osmo_select_main() returns from + * select(2) and calls per-fd callback functions. This allows users of this + * facility to allocate temporary objects like string buffers, message buffers + * and the like which are automatically free'd when going into the next select() + * system call */ + void *select; +}; + +extern __thread struct osmo_talloc_contexts *osmo_ctx; + +/* short-hand #defines for the osmo talloc contexts (OTC) that can be used to pass + * to the various _c functions like msgb_alloc_c() */ +#define OTC_GLOBAL (osmo_ctx->global) +#define OTC_SELECT (osmo_ctx->select) -- cgit v1.2.3