Chapter 26.6
This commit is contained in:
parent
89ffc2e60a
commit
38e4c37f0f
3 changed files with 18 additions and 1 deletions
|
@ -9,13 +9,20 @@
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#define GC_HEAP_GROW_FACTOR 2
|
||||||
|
|
||||||
void *reallocate(void *pointer, size_t oldSize, size_t newSize) {
|
void *reallocate(void *pointer, size_t oldSize, size_t newSize) {
|
||||||
|
vm.bytesAllocated += newSize - oldSize;
|
||||||
if (newSize > oldSize) {
|
if (newSize > oldSize) {
|
||||||
#ifdef DEBUG_STRESS_GC
|
#ifdef DEBUG_STRESS_GC
|
||||||
collectGarbage();
|
collectGarbage();
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (vm.bytesAllocated > vm.nextGC) {
|
||||||
|
collectGarbage();
|
||||||
|
}
|
||||||
|
|
||||||
if (newSize == 0) {
|
if (newSize == 0) {
|
||||||
free(pointer);
|
free(pointer);
|
||||||
return NULL;
|
return NULL;
|
||||||
|
@ -175,6 +182,7 @@ static void sweep() {
|
||||||
void collectGarbage() {
|
void collectGarbage() {
|
||||||
#ifdef DEBUG_LOG_GC
|
#ifdef DEBUG_LOG_GC
|
||||||
printf("-- gc begin\n");
|
printf("-- gc begin\n");
|
||||||
|
size_t before = vm.bytesAllocated;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
markRoots();
|
markRoots();
|
||||||
|
@ -182,8 +190,12 @@ void collectGarbage() {
|
||||||
tableRemoveWhite(&vm.strings);
|
tableRemoveWhite(&vm.strings);
|
||||||
sweep();
|
sweep();
|
||||||
|
|
||||||
|
vm.nextGC = vm.bytesAllocated * GC_HEAP_GROW_FACTOR;
|
||||||
|
|
||||||
#ifdef DEBUG_LOG_GC
|
#ifdef DEBUG_LOG_GC
|
||||||
printf("-- gd end\n");
|
printf("-- gc end\n");
|
||||||
|
printf(" collected %zu bytes (from %zu to %zu) next at %zu\n",
|
||||||
|
before - vm.bytesAllocated, before, vm.bytesAllocated, vm.nextGC);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -55,6 +55,8 @@ static void defineNative(const char *name, NativeFn function) {
|
||||||
void initVM() {
|
void initVM() {
|
||||||
resetStack();
|
resetStack();
|
||||||
vm.objects = NULL;
|
vm.objects = NULL;
|
||||||
|
vm.bytesAllocated = 0;
|
||||||
|
vm.nextGC = 1024 * 1024;
|
||||||
|
|
||||||
vm.grayCount = 0;
|
vm.grayCount = 0;
|
||||||
vm.grayCapacity = 0;
|
vm.grayCapacity = 0;
|
||||||
|
|
|
@ -24,6 +24,9 @@ typedef struct {
|
||||||
Table globals;
|
Table globals;
|
||||||
Table strings;
|
Table strings;
|
||||||
ObjUpvalue *openUpvalues;
|
ObjUpvalue *openUpvalues;
|
||||||
|
|
||||||
|
size_t bytesAllocated;
|
||||||
|
size_t nextGC;
|
||||||
Obj *objects;
|
Obj *objects;
|
||||||
int grayCount;
|
int grayCount;
|
||||||
int grayCapacity;
|
int grayCapacity;
|
||||||
|
|
Loading…
Reference in a new issue