implement CV using wchan but require spinlock?

hi, thanks for the course, i’m self-studying this course online and hope can get some help.

i know in order to implement cv_wait, we need to release the lock (which was passed in), then make the ‘thread’ sleep, then when the thread been wake up, acquire the lock again.

i was plan to implement CV using wchan, however

void wchan_sleep(struct wchan *wc, struct spinlock *lk);

wechan_sleep require both a wchan AND spinlock, do I have to initialize a spinlock inside CV or is there any quick way to make a thread sleep?

i checked the implementation of wchan_sleep, it used

thread_switch(threadstate_t newstate, struct wchan *wc, struct spinlock *lk)

inside, however, still spinlock required.

there are some very old code online that use wchan_sleep ( which does not require a spinlock) and thread_sleep (but i can not find any code about it).

any help would be greatly appreciated

Hello! It’s good to see someone who is self-studying just like me. :smile:

There are lots of ways to implement synchronization primitives though, if you’re going to use wchan for your cv implementation then yes you need a spinlock.

This might sound complicated but keep in mind and think about :

  1. Lock is meant to protect a “shared state” between multiple threads.
  2. What does the spinlock want to protect?

Also you might want to check out this awesome free OS textbook. This helped me A LOT as a self-learner.

Have fun!

1 Like

nice! Also good to see someone is actually replying me :wink:

i’ll have a look, thanks!