Pthread(Mutex)

Pthread 뮤텍스 -상호 배제 기법
뮤텍스 선언과 초기화
pthread_mutex_t muetex_lock=PTHREAD_MUTEX_INITIALIZER;
뮤텍스 락 걸기/풀기
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
뮤텍스 파괴
int pthread_mutex_destroy(pthread_mutex_t* mutex);
pthread_mutex.c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex_lock=PTHREAD_MUTEX_INITIALIZER;
int g_count;
void* t_function(void* data){
char* thread_name=(char*)data;
pthread_mutex_lock(&mutex_lock);
printf("%s start\n", thread_name);
for(int i=0;i<100000000;i++){
g_count++;
}
printf("%s, g_count=%d\n", thread_name, g_count);
pthread_mutex_unlock(&mutex_lock);
}
int main(void){
pthread_t p_thread1, p_thread2;
int status;
pthread_create(&p_thread1, NULL, t_function, (void*)"Thread 1");
pthread_create(&p_thread2, NULL, t_function, (void*)"Thread 2");
pthread_join(p_thread1, (void*)&status);
pthread_join(p_thread2, (void*)&status);
}

celina@ubuntuserver:~/celina/shell$ ./pthread_mutex2

Thread 2 start

Thread 2, g_count=100000000

Thread 1 start

Thread 1, g_count=200000000

만일 동기화 하지 않았을 시,
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int g_count;
void* t_function(void* data){
char* thread_name=(char*)data;
printf("%s start\n", thread_name);
for(int i=0;i<100000000;i++){
g_count++;
}
printf("%s, g_count=%d\n", thread_name, g_count);
}
int main(void){
pthread_t p_thread1, p_thread2;
int status;
pthread_create(&p_thread1, NULL, t_function, (void*)"Thread 1");
pthread_create(&p_thread2, NULL, t_function, (void*)"Thread 2");
pthread_join(p_thread1, (void*)&status);
pthread_join(p_thread2, (void*)&status);
return 0;
}

Thread 2 start

Thread 1 start

Thread 1, g_count=198394686

Thread 2, g_count=200000000

CentOS와 Mac에서는 pthread_join에 두번째 인자를 (void*)&status로 지정했을 때,
segment fault 발생

Ubuntu Server에서는 segment fault 발생 x