summaryrefslogtreecommitdiff
path: root/memory.c
diff options
context:
space:
mode:
authorPeter Mikkelsen <petermikkelsen10@gmail.com>2022-01-13 19:45:22 +0000
committerPeter Mikkelsen <petermikkelsen10@gmail.com>2022-01-13 19:45:22 +0000
commit50d6dd8b50958271bf1ff13f99dc21d4cd8431f7 (patch)
tree504f2a16f29fefedc7ff0a326475f122d018590a /memory.c
parentb1b55e907a5aaf177344769d2b303351ba936bff (diff)
Implement basic reference counting for arrays, which so they
get freed when not in use anymore.
Diffstat (limited to 'memory.c')
-rw-r--r--memory.c53
1 files changed, 53 insertions, 0 deletions
diff --git a/memory.c b/memory.c
new file mode 100644
index 0000000..adc0466
--- /dev/null
+++ b/memory.c
@@ -0,0 +1,53 @@
+#include <u.h>
+#include <libc.h>
+#include <bio.h>
+
+#include "apl9.h"
+
+int alloccounts = 0;
+
+void
+freearray(Array *a)
+{
+ a->refs--;
+ if(a->refs == 0){
+ /* print("Freeing array: %S (%p)\n", pparray(a), a); */
+ if(a->type == AtypeArray)
+ for(int i = 0; i < a->size; i++)
+ freearray(a->arraydata[i]);
+ free(a->shape);
+ free(a);
+ alloccounts--;
+ }else if(a->refs > 0){
+ /* print("Not freeing (refs=%d): %S (%p)\n", a->refs, pparray(a), a); */
+ }else{
+ print("NEGATIVE REF COUNT! %p\n", a);
+ exits(nil);
+ }
+}
+
+Array *
+allocarray(arrayDataType t, int rank, int size)
+{
+ Array *a = malloc(sizeof(Array));
+ a->rank = rank;
+ a->type = t;
+ a->size = size;
+ a->stranded = 0;
+ a->shape = malloc(sizeof(int) * rank);
+ a->rawdata = malloc(datasizes[t] * size);
+ a->type = t;
+ a->refs = 1;
+ alloccounts++;
+ return a;
+}
+
+void
+incref(Array *a)
+{
+ /* print("INCREF %d->%d %S\n", a->refs, a->refs+1, pparray(a)); */
+ a->refs++;
+ if(a->type == AtypeArray)
+ for(int i = 0; i < a->size; i++)
+ incref(a->arraydata[i]);
+} \ No newline at end of file