我使用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,我能做些什么来改变另一个上下文来执行吗?怎么做?

最佳答案

不幸的是,你所要做的并不起作用,因为(根据setjmp手册):

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

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

关于c - 使用C建立框架,并让它具有erlang之类的 future ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11497995/

10-11 18:17