The open source OpenXR runtime
at main 82 lines 1.3 kB view raw
1// Copyright 2020, Collabora, Ltd. 2// SPDX-License-Identifier: BSL-1.0 3/*! 4 * @file 5 * @brief Slightly higher level thread safe helpers. 6 * @author Jakob Bornecrantz <jakob@collabora.com> 7 * 8 * @ingroup aux_util 9 */ 10 11#pragma once 12 13#include "os/os_threading.h" 14 15 16struct u_threading_stack 17{ 18 struct os_mutex mutex; 19 20 void **arr; 21 22 size_t length; 23 size_t num; 24}; 25 26 27static inline void 28u_threading_stack_init(struct u_threading_stack *uts) 29{ 30 os_mutex_init(&uts->mutex); 31} 32 33static inline void 34u_threading_stack_push(struct u_threading_stack *uts, void *ptr) 35{ 36 if (ptr == NULL) { 37 return; 38 } 39 40 os_mutex_lock(&uts->mutex); 41 42 if (uts->num + 1 > uts->length) { 43 uts->length += 8; 44 uts->arr = (void **)realloc(uts->arr, uts->length * sizeof(void *)); 45 } 46 47 uts->arr[uts->num++] = ptr; 48 49 os_mutex_unlock(&uts->mutex); 50} 51 52static inline void * 53u_threading_stack_pop(struct u_threading_stack *uts) 54{ 55 void *ret = NULL; 56 57 os_mutex_lock(&uts->mutex); 58 59 if (uts->num > 0) { 60 ret = uts->arr[--uts->num]; 61 uts->arr[uts->num] = NULL; 62 } 63 64 os_mutex_unlock(&uts->mutex); 65 66 return ret; 67} 68 69static inline void * 70u_threading_stack_fini(struct u_threading_stack *uts) 71{ 72 void *ret = NULL; 73 74 os_mutex_destroy(&uts->mutex); 75 76 if (uts->arr != NULL) { 77 free(uts->arr); 78 uts->arr = NULL; 79 } 80 81 return ret; 82}