Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

co_yield 实现的一点小问题 #1

Open
liuly0322 opened this issue May 14, 2023 · 0 comments
Open

co_yield 实现的一点小问题 #1

liuly0322 opened this issue May 14, 2023 · 0 comments

Comments

@liuly0322
Copy link

if (co_next->status == CO_NEW)
{
assert(co_next->status == CO_NEW);
((struct co volatile *)current)->status = CO_RUNNING; // fogot!!!
stack_switch_call(&current->stack[STACK_SIZE], current->func, (uintptr_t)current->arg);
((struct co volatile *)current)->status = CO_DEAD;
if (current->waiter)
current = current->waiter;
}

这里在 stack_switch_call 返回后应该重新调度协程,而不是简单的返回到调用 yield 处。

对于现在的实现,若 test2 改为:

struct co *thd3 = co_start("consumer-1", consumer, queue);
struct co *thd4 = co_start("consumer-2", consumer, queue);
struct co *thd1 = co_start("producer-1", producer, queue);
struct co *thd2 = co_start("producer-2", producer, queue);

就会导致 main 函数的执行环境,即 test2() 函数调用无法 co_wait(thd1);,测试会陷入死循环。

一个(可能)可行的修改:

void co_schedule() {
    // switch to co_next
    struct co *co_next = current;
    do {
        co_next = co_next->next;
    } while (co_next->status == CO_DEAD || co_next->status == CO_WAITING);
    current = co_next;

    if (current->status == CO_NEW) {
        ((struct co volatile *)current)->status = CO_RUNNING;
        stack_switch_call(&current->stack[STACK_SIZE], current->func,
                          (uintptr_t)current->arg);
        ((struct co volatile *)current)->status = CO_DEAD;
        if (current->waiter) {
            current = current->waiter;
            longjmp(current->context, 1);
        } else {
            co_schedule();
        }
    } else if (current->status == CO_RUNNING) {
        longjmp(current->context, 1);
    }
}

void co_yield () {
    if (current == NULL)
        co_current_init();

    if (setjmp(current->context) == 0)
        co_schedule();
    else
        return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant