TonyW
TonyW

Reputation: 18875

switch context in C

I am learning how to use ucontext_t in C, and have written the following code. I wish to use an infinite while loop to watch the switching between two contexts (ctx_main, and ctx_thread). But, the context seems to be stuck in the while loop. I am looking for some help with correcting the code. I put my comments in the code below:

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

Upvotes: 0

Views: 3221

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126175

Your main routine sets up a new context, but never switches to it, so revert_main never runs.

You only want to call makecontext once for a give u_context object. So move the call to makecontext out of the loop.

Upvotes: 1

Related Questions