我正在學習如何在C中使用ucontext_t,並編寫了以下代碼。我希望使用無限循環來觀察兩個上下文之間的切換(ctx_main和ctx_thread)。但是,上下文似乎卡在while循環中。我正在尋找一些幫助糾正代碼。我把我的意見在下面的代碼:C中的切換上下文
#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你不會錯過任何東西。 – duskwuff
不,線程只是一個名稱,我不需要使用pthread庫。謝謝 – TonyGW