I'm wondering if it's possible to implement preemptive multitasking of native code within a single process in user space on Linux. (That is, externally pause some running native code, save the context, swap in a different context, and resume execution, all orchestrated by user space but using calls that may enter the kernel.) I was thinking this could be done using a signal handler for SIGALRM
, and the *context()
family but it turns out that the entire *context()
family is async-signal-unsafe so that approach isn't guaranteed to work. I did find a gist that implements this idea so apparently it does happen to work on Linux, at least sometimes, even though by POSIX it's not required to work. The gist installs this as a signal handler on SIGALRM
, which makes several *context()
calls:
void
timer_interrupt(int j, siginfo_t *si, void *old_context)
{
/* Create new scheduler context */
getcontext(&signal_context);
signal_context.uc_stack.ss_sp = signal_stack;
signal_context.uc_stack.ss_size = STACKSIZE;
signal_context.uc_stack.ss_flags = 0;
sigemptyset(&signal_context.uc_sigmask);
makecontext(&signal_context, scheduler, 1);
/* save running thread, jump to scheduler */
swapcontext(cur_context,&signal_context);
}
Does Linux offer any guarantee that makes this approach correct? Is there a way to make this correct? Is there a totally different way to do this correctly?
(By "implement in user space" I don't mean that we never enter the kernel. I mean to contrast with the preemptive multitasking implemented by the kernel.)
*context()
family in POSIX. (Also, this is very OS-specific and I meant this just for Linux. There's no reason an OS couldn't make this possible and I want to know if Linux does make this possible. I updated the title accordingly.) – Kenakenafsetjmp
/longjmp
. (Actually, I intended to do some kind of "exception handling" in C.) I just googled "c setjmp longjmp thread switch". Look, what I found (among others): SO: Multitasking using setjmp, longjmp. (IMHO, he could tagged it with c also, at least...) – Varnado