/*
 *   Copyright Institute of Communication and Computer Systems (ICCS)
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

/**
 * @file   tls_allocator.h
 * @author Ioannis Koutras (joko@microlab.ntua.gr)
 * @date   February 2014
 * @brief  Functions for TLS allocators
 */

#ifndef DEALY_TLS_ALLOCATOR_H_
#define DEALY_TLS_ALLOCATOR_H_

#include <dmmlib/allocator.h>
#include <pthread.h>

/** Variable storing allocator's settings per thread. */
extern __thread allocator_t *tls_allocator;
/** Key to re-use the previous variable for other threads. */
pthread_key_t destruction_key;

/** Struct for head of a singly-linked list for allocator_t nodes */
SLIST_HEAD(allocator_list_head_s, allocator_s);

/** Singly-linked list for allocator_t nodes with a mutex lock */
typedef struct locking_allocator_list_s {
    struct allocator_list_head_s head; /**< The head node. */
    locktype_t lock; /**< The lock. */
} locking_allocator_list_t;

/** List of destructed allocators that can be re-used */
extern locking_allocator_list_t destructed_list;

/** Pushes the soon-to-be-dead thread's allocator state to a list for reuse. */
void push_to_destructed_list(void);

/** Allocates in the heap space and initializes allocator state to be used by a
 *  specific thread. */
allocator_t * initialize_allocator(void);

/** Gets the current thread's allocator. */
void get_tls_allocator(void);

#endif /* DEALY_TLS_ALLOCATOR_H_ */