#include #include #include #define minObjects 100 typedef struct _TestObject TestObject; struct _TestObject { int item; TestObject *parent; volatile int ref; }; TestObject *test_object_new(int item) { TestObject *obj = calloc(1, sizeof(TestObject)); obj->item = item; obj->ref = 1; return obj; } int test_object_get_item(TestObject *o) { if (o != NULL) return o->item; } TestObject *test_object_ref(TestObject *o) { if (o != NULL) { o->ref++; } return o; } TestObject *test_object_unref(TestObject **oo) { if (oo == NULL || *oo == NULL) return NULL; TestObject *o = *oo; if (o != NULL && o->ref-- == 1) { test_object_unref(&(o->parent)); free(o); o = NULL; } return o; } void test_object_set_parent(TestObject *o, TestObject *parent) { test_object_unref(&(o->parent)); o->parent = test_object_ref(parent); } int main (int argc, char ** argv) { int o; int n = 5000000; if (argc > 1) { n = atoi(argv[1]); } int objects = minObjects > n ? minObjects : n; TestObject **latest = calloc(minObjects+1, sizeof(TestObject*)); TestObject *firstObj = test_object_new(0); latest[0] = test_object_ref(firstObj); for (o = 0; o < objects; o++) { TestObject *obj = test_object_new(o+1); if (o % (objects/10) == 0) { printf("Allocated object: %d check %d\n",(o+1),test_object_get_item(obj)); } TestObject *tmp = latest[o%minObjects+1]; test_object_unref(&tmp); latest[o%minObjects+1] = test_object_ref(obj); int idx = ((o/2) % minObjects) + 1; TestObject *my = latest[idx]; while (my == NULL || my == obj) { idx /= 2; my = latest[idx]; } test_object_set_parent(obj, my); test_object_unref(&obj); } for (o = 0; o < minObjects+1; o++) { test_object_unref(&(latest[o])); } test_object_unref(&firstObj); }