【问题标题】:switch context in C在 C 中切换上下文
【发布时间】:2014-02-07 02:22:08
【问题描述】:

我正在学习如何在 C 中使用 ucontext_t,并编写了以下代码。我希望使用无限 while 循环来观察两个上下文(ctx_main 和 ctx_thread)之间的切换。但是,上下文似乎停留在 while 循环中。我正在寻找更正代码的帮助。我将我的 cmets 放在下面的代码中:

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

【问题讨论】:

  • 如果您想使用线程,几乎可以肯定使用 POSIX 线程库会更好。跳过 ucontext 不会丢失任何内容。
  • 不,线程只是一个名字,我不需要使用pthread库。谢谢

标签: c context-switch


【解决方案1】:

您的主例程设置了一个新上下文,但从不切换到它,因此revert_main 永远不会运行。

您只想为给定的 u_context 对象调用一次makecontext。所以把对makecontext的调用移出循环。

【讨论】:

  • 感谢@Chris Dodd。 makecontext 是否也将函数附加到该上下文?
  • make_context 只是设置上下文的 pc 和堆栈指针,以便当它切换到时,它将在一个几乎为空的堆栈上运行函数(仅包含指定的参数)。
猜你喜欢
  • 2021-04-07
  • 2011-07-23
  • 1970-01-01
  • 2013-04-21
  • 2017-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多