int main() { coenv_t env = coroutine_init(); myctx ctx1 = {1}; myctx ctx2 = {2}; myctx ctx3 = {3}; int i; int co1, co2, co3; co1 = coroutine_new(env, cofunc, &ctx1); printf("coroutine_new %d\n", co1); co2 = coroutine_new(env, cofunc, &ctx2); printf("coroutine_new %d\n", co2); co3 = coroutine_new(env, cofunc, &ctx3); printf("coroutine_new %d\n", co3); for (i = 0; i < 10; i++) { coroutine_resume(env, co1); coroutine_resume(env, co2); coroutine_resume(env, co3); } coroutine_uninit(env); getchar(); return 0; }
static void test(struct schedule *S) { struct args arg1 = { 0 }; struct args arg2 = { 100 }; int co1 = coroutine_new(S, foo, &arg1); int co2 = coroutine_new(S, foo, &arg2); printf("main start\n"); while (coroutine_status(S,co1) && coroutine_status(S,co2)) { coroutine_resume(S,co1); coroutine_resume(S,co2); } printf("main end\n"); }
int coroutine_check_timeout( struct schedule * sched, int max_check_num, int life ) { int del_num = 0; time_t now = time(NULL); int check_num = 0; int i = -1; while (check_num < max_check_num && check_num <= sched->cap) { ++check_num; i = sched->last_check_idx; i = (i >= sched->cap || i < 0)? 0: i; sched->last_check_idx = i + 1; struct coroutine * C = sched->co[i]; if (NULL == C) { continue; } if (now - C->create_time >= life) { C->callbacks.ontimeout_(sched, i, C->callbacks.ud_); C->fatal = 1; // 让他执行完, coroutine要检查fatal字段 coroutine_resume(sched, i); ++del_num; } } return del_num; }
int main() { int listenfd, optval = 1; int i; int port = 9500; struct sockaddr_in serveraddr; listenfd = socket(AF_INET, SOCK_STREAM, 0); setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int)); bzero((char *) &serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons((unsigned short)port); bind(listenfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)); listen(listenfd, 1024); make_socket_non_blocking(listenfd); struct schedule * S = coroutine_open(); printf("start..\n"); int co1 = coroutine_new(S, acceptfun, (void *)&listenfd); printf("%d\n", S->cap); printf("%d\n", co1); for(i = 0; i < S->cap; i++) { if(coroutine_status(S, i)) { coroutine_resume(S,i); } if(i == S->cap - 1) i = -1; } coroutine_close(S); close(listenfd); return 0; }
void coroutine_wakeup(struct coroutine *co, uint64_t remains) { assert(co->status == STATUS_ASYNC); coroutine_resume(co, (void*)(uintptr_t)remains); }