82 lines
1.9 KiB
C
82 lines
1.9 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
#include "scratch.h"
|
|
|
|
#if __STDC_VERSION__ >= 201112L /* C11 and above */
|
|
#define thread_local _Thread_local
|
|
#elif defined(__GNUC__)
|
|
#define thread_local __thread
|
|
#else
|
|
#error Unsupported compiler.
|
|
#endif
|
|
|
|
#if defined(__GNUC__)
|
|
#define WEAK __attribute__((weak))
|
|
#endif
|
|
|
|
thread_local arena_t *scratch_arena[4] = { 0 };
|
|
|
|
void scratch_destroy(void)
|
|
{
|
|
for (int s = 0; s < sizeof(scratch_arena) / sizeof(scratch_arena[0]); s++)
|
|
{
|
|
if (scratch_arena[s] == NULL) continue;
|
|
arena_del(scratch_arena[s]);
|
|
scratch_arena[s] = NULL;
|
|
}
|
|
}
|
|
|
|
/*
|
|
* Optionally allocate and return a scratch arena. Make sure that the returned
|
|
* arena is not present in the NULL-terminated list `conflicts`
|
|
*/
|
|
arena_t *__scratch_get(arena_t **conflicts)
|
|
{
|
|
int s = 0;
|
|
|
|
if (conflicts != NULL)
|
|
{
|
|
for (s = 0; s < sizeof(scratch_arena) / sizeof(scratch_arena[0]); s++)
|
|
{
|
|
arena_t **c = conflicts;
|
|
for (; *c != NULL; c++)
|
|
{
|
|
if (*c == scratch_arena[s]) break;
|
|
}
|
|
/* No conflcits found, break out */
|
|
if (*c == NULL) break;
|
|
}
|
|
if (s >= sizeof(scratch_arena) / sizeof(scratch_arena[0]))
|
|
{
|
|
fprintf(stderr, "Out of scratch arenas.\n");
|
|
return NULL;
|
|
}
|
|
}
|
|
|
|
if (scratch_arena[s] == NULL)
|
|
{
|
|
scratch_cleanup_init();
|
|
scratch_arena[s] = arena_new(SCRATCH_DEFAULT_SIZE);
|
|
if (scratch_arena[s] == NULL)
|
|
{
|
|
fprintf(stderr, "Error allocating scratch arena %d.", s);
|
|
return NULL;
|
|
}
|
|
|
|
printf("NEW SCRATCH = %p\n", scratch_arena[s]);
|
|
}
|
|
|
|
return scratch_arena[s];
|
|
}
|
|
|
|
void WEAK scratch_cleanup_init(void)
|
|
{
|
|
static bool init = false;
|
|
for (;!init; init = true)
|
|
{
|
|
printf("Single-threaded mode.\n");
|
|
atexit(scratch_destroy);
|
|
}
|
|
}
|