# Thread Programming
## Pthread Lock/Mutex Routines
use mutex
- declare:pthread_mutex_t
- initialize:pthread_mutex_init()
- destroy:pthread_mutex_destory()
- CS be protected:pthread_mutex_lock() and pthread_mutex_unlock()
```c++
#include “pthread.h”
pthread_mutex mutex;
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex);// enter critical section
Critical Section;
pthread_mutex_unlock(&mutex);// leave critical section
pthread_mutex_destory(&mutex);
```
---
## Condition Variables (CV)
- CV代表一些==條件==讓thread可以
- 等待直到條件發生
- 通知其他正在等待的thread,條件已經發生了
- operations on condition variables
- wait()
- ==Block==直到另一個thread calls ==signal() or broadcast()== on the CV
- signal()
- ==Wake up one thread== waiting on the CV
- broadcast()
- ==Wake up all threads== waiting on the CV
- Pthread
```c
pthread_cond_t// data type
pthread_cond_init ()// initialize
pthread_cond_wait (&theCV, &somelock)
pthread_cond_signal (&theCV)
pthread_cond_broadcast (&theCV)
```
### Example
- 所有的condition variable operation ==MUST be performed while a mutex is locked==
A thread is designed to take action when x=0
Another thread is responsible for decrementing the counter

---
## ThreadPool Implementation
- 很多個thread去queue中搶task,queue空了之後,等,等到有東西之後繼續搶
- crtical section保護dequeue的動作



---
## Synchronized Tools in JAVA
- Synchronized Methods (Monitor)
- 只要有"synchronized"都要==mutual exclusivity==
- Synchronized method uses the==method receiver as a lock==
- 兩個synchronized methods的調用不能交錯在同一個物件上
- 當一個thread正在執行synchronized method for an object,所有其他的thread調用synchronized methods for the same object ==block== 直到第一個thread離開 object
```c++
public class SynchronizedCounter {
private int c = 0;
public synchronized void increment() { c++; }
public synchronized void decrement() { c--; }
public synchronized int value() { return c; }
}
```
- Synchronized Statement (Mutex Lock)
- Synchronized blocks uses the ==expression== as a lock
- 一個synchronized Statement只能當thread已經得到lock for the object或者是class that has been referred to in the statement,才能被執行
- useful for improving concurrency with [fine-grained](https://hackmd.io/s/BJ2Vl5JbG#2-ways-to-multithread)
```c++
// p1是會產生race condition的shared variable
// compiler在看到synchronized會自動在前面與後面加lock與unlock
public void run() {
synchronized(p1) {
int i = 10; // statement without locking requirement
p1.display(s1);
}
}
```