스레드를 인터럽트하고 우선 순위에 따라 스레드를 전환하는 타이머를 사용하는 선점 형 사용자 공간 스레드 스케줄러를 구축 중입니다. 그러나 스레드가 인터럽트되면 완료 할 수 없습니다. 다시 시작하십시오. swapcontext를 사용해도 가능한지 묻고 있습니까? itake5seconds()를 완료해야하는이 코드의 결과는 "Hello"메시지를 계속 반복합니다.swapcontext()를 사용하여 함수의 실행을 다시 시작할 수 있습니까?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <ucontext.h>
static ucontext_t mainc, newthread;
void itake5seconds()
{
puts("Hello. I take 5 seconds to run.");
sleep(5);
puts("And I'm done! Wasn't that nice?");
}
void timer_handler(int signum)
{
puts("Doing some scheduler stuff.");
swapcontext(&mainc, &newthread);
}
int main(int argc, char* argv[])
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &timer_handler;
sigaction(SIGALRM, &sa, NULL);
getcontext(&newthread);
newthread.uc_stack.ss_sp = malloc(5000);
newthread.uc_stack.ss_size = 5000;
newthread.uc_link = &mainc;
makecontext(&newthread, &itake5seconds, 0);
struct itimerval timer;
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 500000;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 500000;
setitimer(ITIMER_REAL, &timer, NULL);
while(1);
return 0;
}
누구나 볼 수 있도록 업데이트 된 코드를 제공 할 수 있습니까? – Mike