0

我正在尝试创建用户级线程。这是我的代码示例。任何机构都可以帮助我这个程序中的问题是什么。

#include<stdio.h>
#include<ucontext.h>

int thread_counter = 0;
int thread1, thread2;
int who_am_i;

struct TCB {
    ucontext_t context;
    void (* fun_ptr)();
};
struct TCB tcb[3];
char stack[2][8192];


//----------------------
int thread_create(void (*fun)()) {
    static volatile int s;
    thread_counter++;
    s = 0;
    getcontext(&tcb[thread_counter].context);

    if(!s) {
        tcb[thread_counter].context.uc_stack.ss_sp   = stack[thread_counter];
        tcb[thread_counter].context.uc_stack.ss_size = sizeof(stack[thread_counter]);
        tcb[thread_counter].context.uc_link          = &tcb[0].context;
        tcb[thread_counter].fun_ptr                  = fun;
        s = 1;
    }
    else {
        tcb[who_am_i].fun_ptr();
    }

    return thread_counter;
}


void thread_yield(int next_thread) {
    static volatile int switched;
    switched = 0;
    getcontext(&tcb[who_am_i].context);

    if(!switched) {
        switched = 1;
        who_am_i = next_thread;
        setcontext(&tcb[next_thread].context);
    }
}


//----------------------
void f1() {
    printf("start f1\n");
    thread_yield(thread2);
    printf("finish f1:\n");
}

void f2() {
    printf("start f2\n");
    thread_yield(thread1);
    printf("finish f2\n");
}


//----------------------
int main() {
    thread1 = thread_create(f1);
    thread2 = thread_create(f2);

    who_am_i = 0;
    thread_yield(thread1);
    return 0;
}

线程未正确切换。当我运行它时,它会给出以下输出:

start f1
start f2
finish f2

谢谢

4

1 回答 1

0

你有一个未定义的行为情况。

thread_create你增加thread_counter你做的第一件事。因此,当您创建第二个线程thread_counter时将2. 然后你访问stack[2]它会给你未定义的行为。


您还将uc_link上下文的成员硬编码为&tcb[0].context,由于您的“过早”增量,它永远不会被初始化thread_counter

但主要问题是您实际上并没有创建新的上下文,您只是获取当前线程的上下文。您应该makecontext改为使用每个线程。

于 2013-02-19T08:33:11.100 回答