0

我使用 sigsetjmp/siglongjmp 来更改 progame 堆栈。这是演示:

#include <stdio.h>
#include <stddef.h>
#include <setjmp.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#define POOLSIZE 4096
int active = 0;
int total = 0;

struct thread
{
    int tid;
    sigjmp_buf env;
    char buf[4096];
    int state;
    ssize_t size;
};

struct thread *thread_pool = 0L;
char* anchor_beg = 0L;
char* anchor_end = 0L;
void(*new_thread)(int) = 0L;


void sig_call(int sig)
{
    char anchor;
    anchor_end = &anchor;
    if(sigsetjmp(thread_pool[active].env, 0) == 0)
    {
        thread_pool[active].size = anchor_beg - anchor_end;
        memcpy(thread_pool[active].buf, anchor_end, thread_pool[active].size);
        siglongjmp(thread_pool[0].env, 1);
    }
    else
    {
        memcpy(anchor_beg - thread_pool[active].size, thread_pool[active].buf, thread_pool[active].size);
    }
}

void thread_new(void(*pfn)(int))
{
    alarm(0);
    new_thread = pfn;
    thread_pool[0].state = 2;
//    printf("create new thread:%d\n", total + 1);
    raise(SIGUSR1);
}

void test(int thread)
{
    int i = 0; 
    for(;i != 1000000; i++)
    {
    }
}

void thread_main(int thread)
{
    int i = 0;
    for(i = 0; i < 4000; i++)
        thread_new(test);
}

void call(void(*pfn)(int))
{
    active = ++ total;
    thread_pool[active].tid = active;
    thread_pool[active].state = 1;
    ualarm(500, 0);
    pfn(active);
    thread_pool[active].state = 0;
}

void dispatcher()
{
    thread_pool = (struct thread*)malloc(sizeof(struct thread) * POOLSIZE);
    char anchor;
    anchor_beg = &anchor;
    thread_pool[0].tid = 0;
    thread_pool[0].state = 1;
    if(sigsetjmp(thread_pool[0].env, 0) == 0)
    {
        signal(SIGUSR1, sig_call);
        signal(SIGALRM, sig_call);

        call(thread_main);
    }
    else if(thread_pool[0].state == -1)
    {
        return;
    }
    else if(thread_pool[0].state == 2)
    {
        thread_pool[0].state = 1;
        call(new_thread);
    }

    while(1)
    {
        int i, alive = 0;
        for(i = 1; i <= total; i++)
        {
            if(thread_pool[i].state == 1)
            {
                alive ++;
                ualarm(500, 0);
                active = thread_pool[i].tid;
                siglongjmp(thread_pool[i].env, 1);
            }
        }
        if(alive == 0)
            return;
    } 

}


int main()
{
    dispatcher();
}

这里有什么问题吗?当我想调用一些第三方接口时,也许它是一个块 I/O,我可以做些什么来改变另一个上下文来执行吗?如何?

4

1 回答 1

3

不幸的是,您尝试做的事情不起作用,因为(根据setjmp手册):

 The longjmp() routines may not be called after the routine which called
 the setjmp() routines returns.

这是因为setjmp/longjmp系列函数(包括sig变体)不保留进程堆栈的全部内容。

于 2012-07-16T05:07:30.407 回答