Thread Synchronization
공유 계좌에 두 명의 사용자가 동시에 다른 곳에서 출금을 하려고 한다면 ?
int withdraq(account, amount)
{
balance = get_balance(account);
balance = balance - amount;
put_blance(account, balance);
return balance;
}
출금중인 계좌의 잔고가 update되기전에 출금을 시도하면 계좌는 먼저 출금시도한 사람의 금액이 고려되지 않고 오류가 발생한다.
Mutex
thread에서 동기화를 제공해주는 주요 수단
- lock처럼 동작을 하는 변수
- 공유되는 data에 lock을 걸어서 data를 독점한다.
concept
- 다수의 thread가 존재할 경우 한번에 하나의 thread에서만 mutex를 얻을 수 있다. lock할 수 있다.
- 얻지못한 다른 thread는 mutex를 unlock할 때까지 mutex를 소유할 수 없다.
- thread는 보호된 data에 접근하기 위해서 번걸아가면서 접근해야한다.
critical section은 동기화를 만족시켜주기위해서 상호배제해야한다. mutaually exclusive.
/* mutex object creation & destruction */
int pthread_mutex_init (*mutex, *attr);
int pthread_mutex_destroy (*mutex);
/* mutex attribute creation & destruction */
int pthread_mutexattr_init (*attr);
int pthread_mutexattr_destroy (*attr);
pthread_mutex_t *mutex
pthread_mutexattr_t *attr
mutex를 사용하기 위해서 pthread_mutex_t 변수를 선언하고 pthread_mutexattr_t *attr 속성 설정하고 pthread_mutex_init로 초기화 해주어야한다. 그러면 mutex는 unlock된 상태가 된다. |
mutex : mutex변수 attr : 속성 • protocol – specifies the protocol used to prevent priority inversions for a mutex. priority inversions을 막기 위해서 어떤 protocol를 쓴건가 • prioceiling – specifies the priority ceiling of a mutex. mutex의 우선순위에 대한 ceilling값을 얼마로 지정할 것인가 • process-shared – specifies a mutex which is shared b/w processes process사이에서 어떻게 공유를 할 것인가 기본설정 NULL로 사용해 그냥 ~ |
return |
z.B.) pthread_mutex_t mymutex = THREAD_MUTEX_INITIALIZER; pthread_mutex_init(mutex, attr) |
int pthread_mutex_lock(*mutex);
int pthread_mutex_trylock(*mutex);
int pthread_mutexattr_unlock(*mutex);
pthread_mutex_t *mutex
pthread_mutexattr_t *attr
- lock을 얻기 위해서 : 실패했을 경우 unlock될 때까지 block된다. - lock을 얻기 위해서 : block되지 않고 그냥 리턴 - 현재 mutex를 unlock해주기 위해 : 이미 unlock상태면 error, 내 lock이 아니면 error |
mutex : mutex변수 |
return 0 / error number |
'시스템 프로그래밍' 카테고리의 다른 글
시스템 프로그래밍 7장 - Record Lock (0) | 2020.05.06 |
---|---|
시스템 프로그래밍 7장 - Thread : Condition variable (0) | 2020.05.06 |
시스템 프로그래밍 6장 - Thread : Cancellation (0) | 2020.05.06 |
시스템 프로그래밍 6장 : Thread (0) | 2020.05.06 |
시스템 프로그래밍 5장 - Process Control : Daemon (0) | 2020.05.05 |