Week 30

 CST-334 Week 6

This is our sixth week in CST-334, also known as Operating Systems.

Operating Systems: Three Easy Pieces

This week we read chapters 30-32 of our textbook.

Chapter 30: Condition Variables

Chapter 30 discusses condition variables.

Key Takeaways:

  • Threads can use condition variables to check if a condition is true before executing.
  • Condition variables are queues that threads can wait on. Waiting threads can then be woken when the condition variable changes.
  • The function pthread_cond_wait(cond, mutex) adds a thread to the queue, releases the lock, and puts it to sleep. Cond is the condition variable. Mutex is the lock.
  • The function pthread_cond_signal(cond) wakes the next thread in the queue and gives it the lock. Cond is the condition variable.
  • You should use while loops instead of if statements when checking a condition variable. 

Chapter 31: Semaphores

Chapter 31 discusses semaphores.

Key Takeaways:

  • A semaphore is an object that contains an integer. It is used as both a lock and condition variable.
  • The function sem_init(m, 0, x) initializes a semaphore. M is the semaphore. 0 indicates that the semaphore will be shared between threads. X is the starting value of the semaphore.
  • The function sem_wait(m) decrements the semaphore and either returns if the semaphore was 1 or higher, or puts the thread to sleep. M is the semaphore.
  • The function sem_post(m) increments the semaphore and wakes one of the threads waiting on the semaphore. M is the semaphore.
  • When a semaphore is negative, the value is equal to the number of threads waiting on said semaphore.

Chapter 32: Concurrency Bugs

Chapter 32 discusses common concurrency bugs in concurrent programs.

Key Takeaways:

  •  Atomicity-violation bugs happen when a section of code is intended to be atomic is run un-atomically. Locks can be used to prevent them.
  • Order-violation bugs happen when code that is intended to run in a certain order, such as one thread 1 running before thread 2, runs in an intended order, such as thread 2 running before thread 1. Condition variables can be used to prevent them. 
  • A large portion of non-deadlock bugs are atomicity or order violations.
  • Deadlock occurs when threads are waiting for other threads to release locks while the threads themselves are holding the locks being waited on.
  • Four conditions need to be true for Deadlock to occur:
    • Mutual exclusion
    • Hold-and-wait
    • No preemption
    • Circular wait
  • To prevent deadlocks one can:
    • Order lock acquisition to prevent circular waiting.
    • Acquire all locks at once to prevent hold-and-wait.
    • Preempt locks.
    • Eliminate the need for mutual exclusion.
  • Deadlocks can be avoided by scheduling threads so that no threads require the same locks at the same time. 

 

Comments

Popular posts from this blog

Week 11

Week 12

Week 19