Hey all. I'm having some trouble doing some simple thread implementation. I have two functions, thread_libinit and thread_create. thread_libinit is called first to initialized the library by creating a few necessary threads. The first thread I want it to create is a "garbage collector" of sorts and the second thread calls the main program that's using the library's initialization function.

Here's the problem, I'm getting a segfault on setcontext. This doesn't make sense to me because I'm pretty sure I'm setting this up the right way. When I use the debugger I see it makes the garbage collector thread, then tries to create the main thread but when it gets to the setcontext, it seems to get thrown somewhere above that, because it prints the Creating Thread line twice. When I put in a breakpoint it always jumps back to the breakpoint. Something screwy is going on.

struct Thread
	char* stack;
	ucontext_t* ucontext_ptr;
	int id;

Thread* cleanup;

int thread_libinit(thread_startfunc_t func, void *arg)
	//Initialize the first ID
	id = -1;

	//Check if we've initialized already
                //Creates a garbage collector thread
		initAlready = true;
                //Creates the thread that initializes the main program
	else return -1;

int thread_create(thread_startfunc_t func, void *arg)
	cout << "Creating Thread " << id << endl;
	Thread* t = new Thread;
	t->id = id;
	t->ucontext_ptr = new ucontext_t;
	t->stack = new char[STACK_SIZE];
	t->ucontext_ptr->uc_stack.ss_sp = t->stack;
	t->ucontext_ptr->uc_stack.ss_size = STACK_SIZE;
	t->ucontext_ptr->uc_stack.ss_flags = 0;
		cleanup = t;	
		t->ucontext_ptr->uc_link = NULL;
	else t->ucontext_ptr->uc_link = cleanup->ucontext_ptr;
	readyQueue.push_back(t);//Add thread to queue of ready threads
		setcontext(t->ucontext_ptr);//only if it's the thread that I need to initialize the main program, do I want it to run as soon as it's created.