Thread 동기화
■ Mutex 함수
- mutex 잠금 객체를 만드는 함수 : pthread_mutex_init()
- mutex 잠금을 얻는 함수 : pthread_mutex_lock()
- mutex 잠금을 되돌려주는 함수 : pthread_mutex_unlock()
- mutex 잠금 객체를 제거하는 함수 : pthread_mutex_destroy()
■ pthread_mutex_init()
1 2 | #include<ptrhead.h> int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutex_attr *attr); |
mutex : mutex 잠금 객체
mutex_attr : 이 값을 이용해서 mutex 타입을 결정할 수 있음. NULL 일 경우 기본값이 fast가 설정됨
(fast, recursive , error checking)
fast : 하나의 쓰레드가 하나의 작믐만을 얻을 수 있는 일반적인 형태
recursive : 잠금을 얻은 쓰레드가 다시 잠금을 얻을 수 있다. 이 경우 잠금에 대한 카운트가 증가함
■ pthread_mutex_lock()
1 2 | #include<ptrhead.h> int pthread_mutex_lock(pthread_mutex_t *mutex); |
만약 mutex 잠금을 선점한 쓰레드가 있다면, 선점한 쓰레드가 mutex 잠금을 되돌려주기 전까지 이 코드에서 대기함
■ pthread_mutex_trylock()
1 2 | #include<ptrhead.h> int pthread_mutex_trylock(pthread_mutex_t *mutex); | cs |
대기하지 않고 잠금을 얻을 수 있는지만 체크하는 함수
■ pthread_mutex_lock()
1 2 | #include<ptrhead.h> int pthread_mutex_unlock(pthread_mutex_t *mutex); | cs |
mutex 잠금을 돌려줌(mutex 끄기)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #include<stdio.h> #include<unistd.h> #include<pthread.h> int ncount; //쓰레드간 공유되는 자원 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //뮤텍스 객체 //쓰레드 함수1 void* do_loop(void* data) { int i; pthread_mutex_lock(&mutex); //잠금 생성 for (i = 0; i < 10; i++) { printf("loop1 : %d\n", ncount); ncount++; sleep(1); } pthread_mutex_unlock(&mutex); //잠금 해제 } //쓰레드 함수2 void* do_loop2(void *data) { int i; //잠금을 얻으려고 하지만 do_loop에서 이미 잠금을 얻었으므로 잠금해제를 기다림 pthread_mutex_lock(&mutex); //잠금 생성 for (i = 0; i < 10; i++) { printf("loop2 : %d\n", ncount); ncount++; sleep(1); } pthread_mutex_unlock(&mutex); //잠금 해제 } int main() { int thr_id; pthread_t p_thread[2]; int status; int a = 1; ncount = 0; thr_id = pthread_create(&p_thread[0], NULL, do_loop, (void*)&a); sleep(1); thr_id = pthread_create(&p_thread[1], NULL, do_loop2, (void*)&a); pthread_join(p_thread[0], (void*)&status); pthread_join(p_thread[1], (void*)&status); status = pthread_mutex_destroy(&mutex); printf("code = %d\n", status); printf("programming is end\n"); return 0; } | cs |
반응형
'잡다한 IT > 운영체제' 카테고리의 다른 글
polling 과 spin lock (0) | 2018.08.28 |
---|---|
pthread 관련 함수-1 (0) | 2018.08.16 |
MMU 와 MPU 의 차이점 (0) | 2018.07.11 |
물리 메모리 관리 (0) | 2018.05.04 |
스케줄링 고려할 점 (0) | 2018.05.02 |