---
# System prepended metadata

title: 並行程式設計

---

# 並行程式設計

NP: non-portable

本篇為此課程的筆記: Ref: [並行程式設計](https://hackmd.io/@sysprog/concurrency/https%3A%2F%2Fhackmd.io%2F%40sysprog%2FS1AMIFt0D)

```clike=
    /*
     * mod N 是一種乘除運算，很耗運算資源
     * 若N為2^n其實可以改用 &
     * 
     * */
     
     若 N=2^n
        [a mod N] = [a&(N-1)]

```
---

Linux kernel Completion
* 是一種特別的lock

---
[Ring Buffer](https://github.com/angrave/SystemProgramming/wiki/Synchronization%2C-Part-8%3A-Ring-Buffer-Example)

```clike=
#include <pthread.h>
#include <semaphore.h>
// N must be 2^i
#define N (16)

void *b[N]
int in = 0, out = 0
p_m_t lock = PTHREAD_MUTEX_INITIALIZER// must init!!!
sem_t countsem, spacesem

void init() {
  sem_init(&countsem, 0, 0)//@0: sem, @1 process free?, @2: counter
  sem_init(&spacesem, 0, 16)
}

enqueue(void *value){
 // wait if there is no space left:
 sem_wait( &spacesem )

 p_m_lock(&lock)
 b[ (in++) & (N-1) ] = value
 p_m_unlock(&lock)

 // increment the count of the number of items
 sem_post(&countsem)
}

void *dequeue(){
  // Wait if there are no items in the buffer
  sem_wait(&countsem)

  p_m_lock(&lock)
  void *result = b[(out++) & (N-1)]
  p_m_unlock(&lock)

  // Increment the count of the number of spaces
  sem_post(&spacesem)

  return result
}

}
```