1 /* -----------------------------------------------------------------------------
2 * $Id: Weak.c,v 1.22 2002/04/19 10:23:43 simonmar Exp $
4 * (c) The GHC Team, 1998-1999
6 * Weak pointers / finalizers
8 * ---------------------------------------------------------------------------*/
10 #include "PosixSource.h"
19 StgWeak *weak_ptr_list;
22 * finalizeWeakPointersNow() is called just before the system is shut
23 * down. It runs the finalizer for each weak pointer still in the
26 * Careful here - rts_evalIO might cause a garbage collection, which
27 * might change weak_ptr_list. Must re-load weak_ptr_list each time
32 finalizeWeakPointersNow(void)
36 while ((w = weak_ptr_list)) {
37 weak_ptr_list = w->link;
38 if (w->header.info != &stg_DEAD_WEAK_info) {
39 w->header.info = &stg_DEAD_WEAK_info;
40 IF_DEBUG(weak,fprintf(stderr,"Finalising weak pointer at %p -> %p\n", w, w->key));
41 if (w->finalizer != &stg_NO_FINALIZER_closure) {
42 rts_evalIO(w->finalizer,NULL);
49 * scheduleFinalizers() is called on the list of weak pointers found
50 * to be dead after a garbage collection. It overwrites each object
51 * with DEAD_WEAK, and creates a new thread to run the pending finalizers.
53 * This function is called just after GC. The weak pointers on the
54 * argument list are those whose keys were found to be not reachable,
55 * however the value and finalizer fields have by now been marked live.
56 * The weak pointer object itself may not be alive - i.e. we may be
57 * looking at either an object in from-space or one in to-space. It
58 * doesn't really matter either way.
60 * Pre-condition: sched_mutex _not_ held.
64 scheduleFinalizers(StgWeak *list)
71 /* count number of finalizers first... */
72 for (n = 0, w = list; w; w = w->link) {
73 if (w->header.info != &stg_DEAD_WEAK_info &&
74 w->finalizer != &stg_NO_FINALIZER_closure)
80 IF_DEBUG(weak,fprintf(stderr,"weak: batching %d finalizers\n", n));
82 arr = (StgMutArrPtrs *)allocate(sizeofW(StgMutArrPtrs) + n);
83 SET_HDR(arr, &stg_MUT_ARR_PTRS_FROZEN_info, CCS_SYSTEM);
86 for (n = 0, w = list; w; w = w->link) {
87 if (w->header.info != &stg_DEAD_WEAK_info &&
88 w->finalizer != &stg_NO_FINALIZER_closure) {
89 arr->payload[n] = w->finalizer;
94 // A weak pointer is inherently used, so we do not need to call
97 // Furthermore, when PROFILING is turned on, dead weak
98 // pointers are exactly as large as weak pointers, so there is
99 // no need to fill the slop, either. See stg_DEAD_WEAK_info
100 // in StgMiscClosures.hc.
102 SET_HDR(w, &stg_DEAD_WEAK_info, w->header.prof.ccs);
105 t = createIOThread(RtsFlags.GcFlags.initialStkSize,
108 (StgClosure *)runFinalizerBatch_closure,