Skip to content

[Question] 为什么第八章 并发中的condvar.wakup不直接带上mutex? #94

Open
@nkbai

Description

@nkbai

https://learningos.github.io/rust-based-os-comp2022/chapter8/4condition-variable.html 中,
conditional variable 的wakeup函数是不带任何参数的,例如:

unsafe fn first() -> ! {
     mutex.lock();
     A=1;
     condvar.wakup();
     mutex.unlock();
 
 }

为什么不直接设计成下面的样子呢?

unsafe fn first() -> ! {
     mutex.lock();
     A=1;
/*
     condvar.wakup();
     mutex.unlock();
  这两句话,替换成下面的一句
*/
     condvar.wakup(mutex);
 
 }

好处是,避免了second被唤醒以后,发现获取不到锁而再次休眠。

Activity

chyyuu

chyyuu commented on Jul 29, 2022

@chyyuu
Member

老的写法是希望直观地表达通过条件变量实现同步是需要互斥锁的。

而你的写法
condvar.wakup(mutex);
虽然少了一条语句,但并没有直观表达出何时执行unlock(mutex)操作的过程。
如果把wakup(mutex)的实现也写出来,那和老的两步的写法也没啥差别了。

所以,我个人觉得老的写法相对比较直观。

https://learningos.github.io/rust-based-os-comp2022/chapter8/4condition-variable.html 中, conditional variable 的wakeup函数是不带任何参数的,例如:

unsafe fn first() -> ! {
     mutex.lock();
     A=1;
     condvar.wakup();
     mutex.unlock();
 
 }

为什么不直接设计成下面的样子呢?

unsafe fn first() -> ! {
     mutex.lock();
     A=1;
/*
     condvar.wakup();
     mutex.unlock();
  这两句话,替换成下面的一句
*/
     condvar.wakup(mutex);
 
 }

好处是,避免了second被唤醒以后,发现获取不到锁而再次休眠。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @chyyuu@nkbai

        Issue actions

          [Question] 为什么第八章 并发中的condvar.wakup不直接带上mutex? · Issue #94 · LearningOS/rust-based-os-comp2023