1 /******************************************************************************
3 * Copyright (C) 2014 Google, Inc.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 ******************************************************************************/
19 #define LOG_TAG "bt_osi_future"
23 #include "osi/include/allocator.h"
24 #include "osi/include/future.h"
25 #include "osi/include/osi.h"
26 #include "osi/include/log.h"
27 #include "osi/include/semaphore.h"
30 bool ready_can_be_called;
31 semaphore_t *semaphore; // NULL semaphore means immediate future
35 static void future_free(future_t *future);
37 future_t *future_new(void) {
38 future_t *ret = osi_calloc(sizeof(future_t));
40 LOG_ERROR("%s unable to allocate memory for return value.", __func__);
44 ret->semaphore = semaphore_new(0);
45 if (!ret->semaphore) {
46 LOG_ERROR("%s unable to allocate memory for the semaphore.", __func__);
50 ret->ready_can_be_called = true;
57 future_t *future_new_immediate(void *value) {
58 future_t *ret = osi_calloc(sizeof(future_t));
60 LOG_ERROR("%s unable to allocate memory for return value.", __func__);
65 ret->ready_can_be_called = false;
72 void future_ready(future_t *future, void *value) {
73 assert(future != NULL);
74 assert(future->ready_can_be_called);
76 future->ready_can_be_called = false;
77 future->result = value;
78 semaphore_post(future->semaphore);
81 void *future_await(future_t *future) {
82 assert(future != NULL);
84 // If the future is immediate, it will not have a semaphore
85 if (future->semaphore)
86 semaphore_wait(future->semaphore);
88 void *result = future->result;
93 static void future_free(future_t *future) {
97 semaphore_free(future->semaphore);