---
# System prepended metadata

title: Muti-thread

---

# Muti-thread

![](https://i.imgur.com/3goN0W1.png)




## [Critical Section](https://github.com/angrave/SystemProgramming/wiki/Synchronization,-Part-1:-Mutex-Locks#solving-critical-sections)

## [Race condition](https://zh.wikipedia.org/wiki/%E7%AB%B6%E7%88%AD%E5%8D%B1%E5%AE%B3)

### Data race

Database
Filesystem
共筆

## Mutex and Condition Variabal

### Mutex
> Jserv: 解鈴還需繫鈴人。

## Semaphore

> Semaphore 的本質就是一個 Counter 。

考慮以下程式碼:
```c=
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

static sem_t A_B;
static sem_t B_A;

void *printA(void *arg)
{
	int i = 0;
	for(i = 1;i<11;i++){
		sem_wait(&B_A);
		printf("第%02d次:A",i);
		sem_post(&A_B);
	}
	return NULL;
}
void *printB(void *arg)
{
	int i = 0;
	for(i = 1;i<11;i++){
		sem_wait(&A_B);
		printf("B");
		sem_post(&B_A);
	}
	return NULL;
}
int main(){
	pthread_t thread_A;
	pthread_t thread_B;
	sem_init(&A_B,0,0);
	sem_init(&B_C,0,1);
	pthread_create(&thread_A,NULL,printA,NULL);
	pthread_create(&thread_B,NULL,printB,NULL);
	pthread_join(thread_A, NULL);
	pthread_join(thread_B, NULL);
	sem_destroy(&A_B);
	sem_destroy(&B_C);
	printf("\n");
	return 0;
}
```


## Reference

- [SystemProgramming](https://github.com/angrave/SystemProgramming/wiki)
- [並行和多執行緒程式設計](https://hackmd.io/@sysprog/concurrency/https%3A%2F%2Fhackmd.io%2F%40sysprog%2FS1AMIFt0D?fbclid=IwAR21X-K76f86_xW0814bwYTHjeJg2V67mqy5Zs1PDkoon8m6qQAHEHCMwPQ)
- [Mr.Opengate's Blog](https://mropengate.blogspot.com/search/label/Computer%20Science-Operating%20System)