golang 基于信号实现抢占式调度基本原理
hustxiaoc opened this issue · 1 comments
hustxiaoc commented
#define _GNU_SOURCE 1
#include<iostream>
#include<iomanip>
#include<signal.h>
#include <ucontext.h>
#include <unistd.h>
using std::cout;
static void test() {
cout << "call test function" << std::endl;
}
static volatile int runing = 1;
static void handler(int, siginfo_t *si, void *ptr) {
ucontext_t *uc = (ucontext_t *)ptr;
cout << "ip: 0x" << std::hex << uc->uc_mcontext.gregs[REG_RIP] << '\n';
greg_t sp = uc->uc_mcontext.gregs[REG_RSP];
sp = sp - 8;
*((greg_t*)sp) = uc->uc_mcontext.gregs[REG_RIP];
uc->uc_mcontext.gregs[REG_RIP] = (greg_t)&test;
uc->uc_mcontext.gregs[REG_RSP] = sp;
runing = 0;
}
int main()
{
begin:
cout.setf(std::ios::unitbuf);
cout << getpid() << " ," << &&begin << " ~ " << &&before << " ~ " << &&after << '\n';
struct sigaction s;
s.sa_flags = SA_SIGINFO|SA_RESETHAND;
s.sa_sigaction = handler;
sigemptyset(&s.sa_mask);
sigaction(SIGUSR1, &s, 0);
int i = 0;
before:
do
{
i++;
} while (runing);
cout << "after loop" << std::endl;
after:
cout << "End.\n";
}
hustxiaoc commented
output
21031 ,0x564298dcc40b ~ 0x564298dcc4e1 ~ 0x564298dcc521
si:0x3e800004e9a
ip: 0x564298dcc4e8
call test function
after loop
End.
使用 kill -USR1 21031 发送信号