我正在学习如何在 C 中使用 ucontext_t,并编写了以下代码。我希望使用无限 while 循环来观察两个上下文(ctx_main 和 ctx_thread)之间的切换。但是,上下文似乎陷入了 while 循环中。我正在寻求一些帮助来纠正代码。我把我的评论放在下面的代码中:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ucontext.h>
#define MEM 64000
ucontext_t ctx_main, ctx_thread;
static int thread_id = 0;
/* the function thread_init() will initialize the ctx_main context
* this is the first function to be called in main() */
void thread_init()
{
getcontext(&ctx_main);
ctx_main.uc_link = 0;
ctx_main.uc_stack.ss_sp = malloc(MEM);
ctx_main.uc_stack.ss_size = MEM;
ctx_main.uc_stack.ss_flags = 0;
printf("printed in thread_init()\n");
}
/* This function revert_main is supposed to increment the global variable thread_id,
* then switch back to ctx_main context */
void *revert_main(void *n)
{
thread_id += *(int *) n;
printf("printed in the revert_main()\n");
swapcontext(&ctx_thread, &ctx_main); /* now switch back to ctx_main context */
}
int main()
{
thread_init(); /* Initialize the ctx_main context */
getcontext(&ctx_thread); /* Initialize the ctx_thread context */
ctx_thread.uc_link = 0;
ctx_thread.uc_stack.ss_sp = malloc(MEM);
ctx_thread.uc_stack.ss_size = MEM;
ctx_thread.uc_stack.ss_flags = 0;
int *j = (int *) malloc(sizeof(int));
*j = 1;
while(1) /* Infinite loop to switch between ctx_main and ctx_thread */
{
printf("printed in the main while loop\n");
printf("the thread id is %d\n", thread_id);
makecontext(&ctx_thread, (void *)&revert_main, 1, (void *)j); /* hopefully this will trigger the revert_main() function */
}
return 0;
}
最佳答案
您的主例程设置了一个新上下文,但从未切换到它,因此 revert_main
永远不会运行。
您只想为给定的 u_context 对象调用一次 makecontext
。因此,将对 makecontext
的调用移出循环。
关于c - C语言中切换上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21618120/