Haskell for Imperative Programmers #29 - Semaphores (QSem, QSemN)

Поделиться
HTML-код
  • Опубликовано: 6 ноя 2024

Комментарии • 7

  • @Chemaclass
    @Chemaclass 4 года назад +16

    This is the best Haskell series by far in the whole Internet :D

  • @FourTetTrack
    @FourTetTrack Год назад

    Thanks for the tutorials Philipp!

  • @amr3725
    @amr3725 4 года назад +1

    I'm an undergrad CS student, and you just clearly explained and gave examples of a concept in 2 videos! Something that took my uni one whole module -_-. Thank you for the great content!

  • @RatanSur
    @RatanSur 4 года назад +6

    Yeah, I agree, these videos have been amazing. Great job explaining.

  • @FoxInFlame
    @FoxInFlame 3 года назад +2

    So I vaguely understand Semaphores now, but I'm still lost on the difference between MVar/Chan and this. Semaphores sound like it's complicating MVar/Chan and introduces more problems?

    • @minamagdy4126
      @minamagdy4126 Год назад +2

      Sure, regular semaphore seems underwhelming, but there are two advantages:
      - syntactic cleanliness for when you don't actually require a resource, but only a race condition
      - being able to know how many resources are available in a channel without grabbing them by using QSemN. Otherwise, a different deadlock can happen.

    • @kostasgkoutis8534
      @kostasgkoutis8534 Год назад

      FoxInFlame, Semaphores are a relatively lower level synchronization construct in comparison to Channels. Semaphores are basically just a simple integer whose increasing or decreasing affects if a thread (or threads) is going to block or not. Channels, on the other hand, can have, generally speaking, other characteristics too (e.g: they can buffer on write, they can prefer newer writes discarding older ones etc.) Every language designs Channels differently but their API allows much more options than the API of a Semaphore. MVar (seems to be) is an atomic variable that excludes multiple writers, writing while others read, reading while someone writes (readers/writers problem). It can be used as a low-level synchronizer, on par with what a Semaphore(1) + some variable would do. In fact, I wouldn't be surprised if MVar is implemented via QSem under the hood (I didn't check it).
      All in all, what I think he tries to say is that Semaphores being low level synchronizer, can be a good building block for writing concurrent code but they don't prevent you the usual suspects of writing concurrent code erroneously, leading to deadlocks, livelocks, thread starvation etc, because they involve locking. But you can also deadlock yourself with Channels or MVars, i dont get the feeling that he wanted to contrust them with Semaphores. What he probably wanted to do is find a good segway for his next section where he will present STM, a technique writing concurrent code AND lock-free code.