Skip to content

Commit

Permalink
run all finalizers on exit. fixes #3624
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffBezanson committed Jul 5, 2013
1 parent 1998871 commit 4796390
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 16 deletions.
47 changes: 31 additions & 16 deletions src/gc.c
Original file line number Diff line number Diff line change
Expand Up @@ -266,34 +266,49 @@ static void schedule_finalization(void *o)
arraylist_push(&to_finalize, o);
}

static void run_finalizer(jl_value_t *o, jl_value_t *ff)
{
jl_function_t *f;
while (jl_is_tuple(ff)) {
f = (jl_function_t*)jl_t0(ff);
assert(jl_is_function(f));
JL_TRY {
jl_apply(f, (jl_value_t**)&o, 1);
}
JL_CATCH {
}
ff = jl_t1(ff);
}
f = (jl_function_t*)ff;
assert(jl_is_function(f));
jl_apply(f, (jl_value_t**)&o, 1);
}

static void run_finalizers(void)
{
void *o = NULL;
jl_function_t *f=NULL;
jl_value_t *ff=NULL;
JL_GC_PUSH3(&o, &f, &ff);
jl_value_t *ff = NULL;
JL_GC_PUSH2(&o, &ff);
while (to_finalize.len > 0) {
o = arraylist_pop(&to_finalize);
ff = (jl_value_t*)ptrhash_get(&finalizer_table, o);
assert(ff != HT_NOTFOUND);
ptrhash_remove(&finalizer_table, o);
while (jl_is_tuple(ff)) {
f = (jl_function_t*)jl_t0(ff);
assert(jl_is_function(f));
JL_TRY {
jl_apply(f, (jl_value_t**)&o, 1);
}
JL_CATCH {
}
ff = jl_t1(ff);
}
f = (jl_function_t*)ff;
assert(jl_is_function(f));
jl_apply(f, (jl_value_t**)&o, 1);
run_finalizer(o, ff);
}
JL_GC_POP();
}

void jl_gc_run_all_finalizers()
{
for(size_t i=0; i < finalizer_table.size; i+=2) {
if (finalizer_table.table[i+1] != HT_NOTFOUND) {
schedule_finalization(finalizer_table.table[i]);
}
}
run_finalizers();
}

void jl_gc_add_finalizer(jl_value_t *v, jl_function_t *f)
{
jl_value_t **bp = (jl_value_t**)ptrhash_bp(&finalizer_table, v);
Expand Down
3 changes: 3 additions & 0 deletions src/init.c
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,9 @@ DLLEXPORT void uv_atexit_hook()
jl_apply((jl_function_t*)f, NULL, 0);
}
}

jl_gc_run_all_finalizers();

uv_loop_t* loop = jl_global_event_loop();
struct uv_shutdown_queue queue = {NULL, NULL};
uv_walk(loop, jl_uv_exitcleanup_walk, &queue);
Expand Down
1 change: 1 addition & 0 deletions src/julia.h
Original file line number Diff line number Diff line change
Expand Up @@ -1100,6 +1100,7 @@ void *jl_gc_managed_malloc(size_t sz);
void *jl_gc_managed_realloc(void *d, size_t sz, size_t oldsz, int isaligned);
void jl_gc_free_array(jl_array_t *a);
void jl_gc_track_malloced_array(jl_array_t *a);
void jl_gc_run_all_finalizers();
void *alloc_2w(void);
void *alloc_3w(void);
void *alloc_4w(void);
Expand Down

0 comments on commit 4796390

Please sign in to comment.