copying thread code into mem.c