实现简单的绿色线程,如果用libpcl:(适用于VC6)
#include <stdio.h> #include <string.h> #include "pcl.h" static void taskhello(void *arg) { int i; for (i = 0; i < 3; i++) { printf("Hello %d\n", i); co_resume(); } *((int *)arg) = 1; co_resume(); } static void taskworld(void *arg) { int i; for (i = 0; i < 3; i++) { printf("World %d\n", i); co_resume(); } *((int *)arg) = 1; co_resume(); } int main(int argc, char **argv) { coroutine_t co1, co2; int t1 = 0, t2 = 0; co_thread_init(); co1 = co_create(taskhello, &t1, NULL, 32768); co2 = co_create(taskworld, &t2, NULL, 32768); while(1) { if (t1 != 1) { co_call(co1); } if (t2 != 1) { co_call(co2); } if (t1 == 1 && t2 == 1) { co_delete(co1); co_delete(co2); co1 = co2 = NULL; break; } } co_thread_cleanup(); return 0; }
用libtask-win32实现(VC6不支持,需要VC6以上)
#include <stdio.h> #include "task.h" static void taskhello(void *arg) { int i; for (i = 0; i < 3; i++) { printf("Hello %d\n", i); taskyield(); } } static void taskworld(void *arg) { int i; for (i = 0; i < 3; i++) { printf("World %d\n", i); taskyield(); } } void taskmain(int argc, char *argv[]) { taskcreate(taskhello, NULL, 0); taskcreate(taskworld, NULL, 0); } /* output: Hello 0 World 0 Hello 1 World 1 Hello 2 World 2 */
后来仔细想想,发现如果不用绿色线程(纤程),
那么用goto貌似也能实现(传说中的意大利面条)
#include <stdio.h> #include <string.h> #define TASK_MAX 20 struct task_t { int task; int state; }; static void taskhello(void *arg) { static int i[TASK_MAX] = {0}; int task = ((struct task_t *)arg)->task; switch(((struct task_t *)arg)->state) { case -1: goto resume_1; } for (i[task] = 0; i[task] < 3; i[task]++) { printf("Hello %d\n", i[task]); ((struct task_t *)arg)->state = -1; return; resume_1: ; } ((struct task_t *)arg)->state = 1; } static void taskworld(void *arg) { static int i[TASK_MAX] = {0}; int task = ((struct task_t *)arg)->task; switch(((struct task_t *)arg)->state) { case -1: goto resume_1; } for (i[task] = 0; i[task] < 4; i[task]++) { printf("World %d\n", i[task]); ((struct task_t *)arg)->state = -1; return; resume_1: ; } ((struct task_t *)arg)->state = 1; } int main(int argc, char **argv) { struct task_t co1; struct task_t co2; co1.task = 0; co2.task = 1; co1.state = co2.state = 0; while(1) { if(co1.state != 1) { taskhello(&co1); } if(co2.state != 1) { taskworld(&co2); } if (co1.state == 1 && co2.state == 1) { break; } } return 0; }
相关推荐
2. 用table显示n条记录,每3行换一次颜色,即1,2,3用红色字体,4,5,6用绿色字体,7,8,9用红颜色字体。 83 3、HTML 的 form 提交之前如何验证数值文本框的内容全部为数字? 否则的话提示用户并终止提交? 84 4、...
2. 用table显示n条记录,每3行换一次颜色,即1,2,3用红色字体,4,5,6用绿色字体,7,8,9用红颜色字体。 83 3、HTML 的 form 提交之前如何验证数值文本框的内容全部为数字? 否则的话提示用户并终止提交? 84 4...
2. 用table显示n条记录,每3行换一次颜色,即1,2,3用红色字体,4,5,6用绿色字体,7,8,9用红颜色字体。 83 3、HTML 的 form 提交之前如何验证数值文本框的内容全部为数字? 否则的话提示用户并终止提交? 84 4、...
2. 用table显示n条记录,每3行换一次颜色,即1,2,3用红色字体,4,5,6用绿色字体,7,8,9用红颜色字体。 90 3、HTML 的 form 提交之前如何验证数值文本框的内容全部为数字? 否则的话提示用户并终止提交? 91 4、...