[project @ 2000-02-25 17:35:11 by sewardj]
[ghc-hetmet.git] / ghc / rts / Weak.c
1 /* -----------------------------------------------------------------------------
2  * $Id: Weak.c,v 1.13 2000/02/25 17:35:11 sewardj Exp $
3  *
4  * (c) The GHC Team, 1998-1999
5  *
6  * Weak pointers / finalizers
7  *
8  * ---------------------------------------------------------------------------*/
9
10 #include "Rts.h"
11 #include "RtsAPI.h"
12 #include "SchedAPI.h"
13 #include "RtsFlags.h"
14 #include "Weak.h"
15 #include "Storage.h"
16
17 StgWeak *weak_ptr_list;
18
19 /*
20  * finalizeWeakPointersNow() is called just before the system is shut
21  * down.  It runs the finalizer for each weak pointer still in the
22  * system.
23  *
24  * Careful here - rts_evalIO might cause a garbage collection, which
25  * might change weak_ptr_list.  Must re-load weak_ptr_list each time
26  * around the loop.
27  */
28
29 void
30 finalizeWeakPointersNow(void)
31 {
32   StgWeak *w;
33   
34   while ((w = weak_ptr_list)) {
35     weak_ptr_list = w->link;
36     IF_DEBUG(weak,fprintf(stderr,"Finalising weak pointer at %p -> %p\n", w, w->key));
37     w->header.info = &DEAD_WEAK_info;
38     if (w->finalizer != &NO_FINALIZER_closure) {
39       rts_evalIO(w->finalizer,NULL);
40     }
41   }
42
43
44 /*
45  * scheduleFinalizers() is called on the list of weak pointers found
46  * to be dead after a garbage collection.  It overwrites each object
47  * with DEAD_WEAK, and creates a new thread for the finalizer.
48  *
49  * This function is called just after GC.  The weak pointers on the
50  * argument list are those whose keys were found to be not reachable,
51  * however the value and finalizer fields have by now been marked live.
52  * The weak pointer object itself may not be alive - i.e. we may be
53  * looking at either an object in from-space or one in to-space.  It
54  * doesn't really matter either way.
55  */
56
57 void
58 scheduleFinalizers(StgWeak *list)
59 {
60   StgWeak *w;
61   StgTSO *t;
62   
63   for (w = list; w; w = w->link) {
64     IF_DEBUG(weak,fprintf(stderr,"Finalising weak pointer at %p -> %p\n", w, w->key));
65     if (w->finalizer != &NO_FINALIZER_closure) {
66       t = createIOThread(RtsFlags.GcFlags.initialStkSize, w->finalizer);
67       scheduleThread(t);
68     }
69     w->header.info = &DEAD_WEAK_info;
70   }
71 }