gpt4 book ai didi

c - 用C搭建一个框架,让它像erlang一样有 future

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:08 24 4
gpt4 key购买 nike

我使用 sigsetjmp/siglongjmp 来更改程序游戏堆栈。这是演示:

#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();
}

这里有什么问题吗?当我想调用一些第三方接口(interface)时,也许它是一个 block 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com