pthread 여러개 생성 후 join 시 세그먼트 오류...
리눅스로 프로그램을 짜던 도중 막히는 부분이 있어서
제가 짜던 소스에서 문제가 되는 부분만 따로 떼어왔습니다
간단히 설명을 하자면 pthread_create로 예를 들어 10개의 스레드를 생성한 후
pthread_join을 10번을 해주고 각 스레드에서 리턴 값을 받아오는 부분인데요
10개의 생성이 이상 없이 완료되고 join도 하나씩 하고 리턴도 하는데 그러다가
마지막 쓰레드의 join은 수행이 안되고 segmentation fault 가 발생해버리네요
도대체 왜 그러는지 알 수가 없어서 너무 답답하네요요
#include
#include
#include
#include
pthread_mutex_t mutex_lock;
struct arg_struct {
int a;
int b;
};
void *t_function(void *data) {
pthread_mutex_lock(&mutex_lock);
struct arg_struct *arg = (struct arg_struct *)data;
long int s;
s = arg->a;
printf("s에 %d를 저장했습니다\n", s);
pthread_mutex_unlock(&mutex_lock);
return (void **)s;
}
int main()
{
int i;
pthread_t p_thread[2];
int thr_id;
int status;
struct arg_struct arg[2];
for(i = 1; i >= 0; i--) {
arg[i].a = i;
arg[i].b = i;
}
pthread_mutex_init(&mutex_lock, NULL);
printf("스레드 %d 생성 전\n", 1);
thr_id = pthread_create(&p_thread[1],NULL, t_function, (void *)&arg[1]);
printf("스레드 %d 생성 후\n", 1);
usleep(1000);
printf("스레드 %d 생성 전\n", 0);
thr_id = pthread_create(&p_thread[0],NULL, t_function, (void *)&arg[0]);
printf("스레드 %d 생성 후\n", 0);
int temp[2];
printf("스레드 %d 조인 전\n", 1);
pthread_join(p_thread[1], (void**)&status);
printf("스레드 %d 조인 후\n", 1);
temp[1] = status;
printf("스레드 %d 조인 전\n", 0);
pthread_join(p_thread[0], (void**)&status);
printf("스레드 %d 조인 후\n", 0);
temp[0] = status;
printf("%d%d", temp[1], temp[0]);
pthread_mutex_destroy(&mutex_lock);
return 0;
}
이 소스를 돌려도 마찬가지지만 제가 짜던 프로그램에서 비슷하게 돌려보면
..
..
..
값 저장 완료
스레드 3 조인 후
스레드 2 조인 전
값 저장 완료
스레드 2 조인 후
스레드 1 조인 전
값 저장 완료
스레드 1 조인 후
스레드 0 조인 전
세그멘테이션 오류 (core dumped)
이렇게 종료가 되어버립니다
...
status가 int인데 &status를 void**로 캐스팅해서 넘겨 버렸으니, 64비트 머신이면 void*에 해당하는 8바이트 영역에 리턴값이 돌아오겠죠. status는 4바이트일 테니 메모리가 깨집니다.
...
그것이 제 코드의 문제였군요
하지만 왜 마지막 join에서만 문제가 발생하는 걸까요?
그 이전의 join은 제대로 수행이 되는 것 같거든요
...
감.. 사.. 합니다 ㅠㅠㅠ 그 부분은 왜 제 눈에 들어오지 않았을까요
t_function 안에는 long int로 해놓고... status를 long int로 바꾸고 나니 모두 해결입니다! 감사합니다!
댓글 달기