#include <stdio.h>
#include <stdlib.h>
#define _XOPEN_SOURCE 600
#include <ucontext.h>
/* Tests creation.
Should print "Hello World!" */
typedef struct thread_t{
ucontext_t thread_context;
}thread_t;
void *thr1(void *in) {
printf("Hello World!\n");
fflush(stdout);
return NULL;
}
void *thr2(void *in) {
printf("goodbye World!\n");
fflush(stdout);
return NULL;
}
int main() {
thread_t t1;
thread_t t2;
thread_create( &t1, thr1, NULL);
// if you comment out the following line, the program will run like a charm.
thread_create( &t2, thr2, NULL);
setcontext(&t1.thread_context);
return EXIT_SUCCESS;
}
void thread_routine(void *(*start_routine)(void *), void *arg)
{
start_routine(arg);
printf("gtthread routine finished\n");
}
int thread_create(thread_t *thread,
void *(*start_routine)(void *),
void *arg){
if (getcontext(&(thread->thread_context)) == -1)
{
perror("getcontext");
}
thread->thread_context.uc_stack.ss_sp = (char*) malloc(SIGSTKSZ);
thread->thread_context.uc_stack.ss_size = SIGSTKSZ;
thread->thread_context.uc_link = NULL;
makecontext(&(thread->thread_context), thread_routine, 2, (void *)start_routine, arg);
}
I run my code in OS X 10.10 with gcc. I am trying to implement a usercontext library.
If I comment out thread_create( &t2, thr2, NULL);
, the code will produce desired effect. I have no idea why a line related to t2
will lead to segmentation fault of t1
.
Author's Notes
I happily work on implementing a usercontext library after switching to Ubuntu. Everything works fine. No segmentation fault anymore. And as expected, it crashes on OS X 10.10.
My guess would be that since makecontext(), swapcontext(), and etc. is deprecated on OS X since 10.6 as warned by compiler, I shouldn't expect that it will work.