-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.c
116 lines (88 loc) · 1.7 KB
/
test.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
* Copyright (c) 2008 ,
* Cloud Wu . All rights reserved.
*
* http://www.codingnow.com
*
* Use, modification and distribution are subject to the "New BSD License"
* as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
*/
#include "gc.h"
#include <stdlib.h>
#include <stdio.h>
struct test {
struct test *next;
};
static void
log_ptr(void *p)
{
printf("free %p\n",p);
}
static struct test *
new_test(struct test *parent)
{
struct test *ret=(struct test*)gc_malloc(sizeof(struct test),parent,log_ptr);
printf("new %p\n",ret);
if (parent) {
ret->next=parent->next;
parent->next=ret;
}
else {
ret->next=0;
}
return ret;
}
static void *
test(struct gc_weak_table *weak)
{
struct test *p;
int i;
gc_enter();
gc_enter();
for (i=0;i<4;i++) {
p=new_test(0);
gc_link(weak,0,p);
}
/* after gc_leave , only last p leave in the stack */
gc_leave(p,0);
/* p will not be collected */
gc_collect();
p->next=new_test(p);
/* one node can be linked to parent more than once */
gc_link(p,0,p->next);
gc_dryrun();
gc_link(p,p->next,0);
gc_dryrun();
/* p will not be exist on the stack after gc_leave , it can be collected. */
gc_leave(p->next,0);
gc_link(weak,0,p->next);
return p->next;
}
static void
iterate_weak_table(struct gc_weak_table *weak)
{
int iter=0;
void *p;
gc_enter();
while ((p=gc_weak_next(weak,&iter)) != 0) {
printf("%p is alive\n",p);
}
gc_leave(0);
}
int
main()
{
struct test *p;
struct gc_weak_table *weak;
gc_init();
weak=gc_weak_table(0);
p=test(weak);
gc_enter();
printf("%p is in weak table\n",gc_weak_next(weak,0));
gc_leave(0);
gc_collect();
iterate_weak_table(weak);
gc_dryrun();
gc_exit();
return 0;
}