Skip to content
Snippets Groups Projects
Commit 02e0714b authored by BeomSooHeo's avatar BeomSooHeo
Browse files

thread

parent f156759a
Branches
No related tags found
No related merge requests found
#include <stdio.h>
#include <string.h>
#include <pthread.h>
void* sth_1(void * args){
int result = 0;
short * p = (short *)args;
for(int i =0 ; i<30; i++) result += *(p+i);
printf("\n\nSum of scores : %d\n", result);
printf("\nAverage of scores : %.2f\n", result/30.0f);
printf("\n---------------- thread_1 terminated ----------------\n");
pthread_exit(NULL);
}
void* sth_2(void * args){
short * p = (short *)args;
for(int i = 0; i< 30 ; i++)
for(int j = 0 ; j< 29-i ; j++){
if(*(p+j) < *(p+j+1)) {
short tmp = *(p+j);
*(p+j) = *(p+j+1);
*(p+j+1) = tmp;
}
}
printf("\n\n---------------- Score list by desc ----------------\n\n");
for(int n = 0; n <30 ; n++) printf("%hd :%hd \n",(n+1),*(p+n));
printf("\n---------------- thread_2 terminated ----------------\n");
pthread_exit(NULL);
}
int main() {
short scores[30];
pthread_t th1, th2;
printf("******* Enter Scores ******\n");
for(int i = 0; i< 30 ; i++) scanf("%hd", &scores[i]);
printf("You Entered: ");
for(int i = 0; i< 30 ; i++) printf("%d ", scores[i]);
pthread_create(&th1, NULL, sth_1, (void *)scores);
pthread_create(&th2, NULL, sth_2, (void *)scores);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
printf("\n---------------- main thread terminated ----------------\n");
pthread_exit(NULL);
}
\ No newline at end of file
# thread
## 1. discription
Input: 사용자로부터 short형 정수 30개를 입력 받는다.
main function:
Thread를 2개 생성하고 thread가 종료될 때까지 기다린다.
Thread sth_1 :
전달받은 void 형 포인터를 short형 포인터로 변환한 후
포인터가 가리키는 배열의 모든 element의 총합과
이를 평균을 낸 결과를 출력한다.
Thread sth_2 :
전달받은 void 형 포인터를 short형 포인터로 변환한 후
bubble_sort를 통해 포인터가 가리키는 배열의 모든 element를 내림차순 정렬한 후 출력한다.
## 2. result
[사진1]
<br>
pthread.h를 사용하기 위해서
gcc 컴파일시 -lpthread 링크 설정을 해주어야한다.
[사진2]
<br>
1부터 30까지 입력을 하였고,
입력이 제대로 이뤄졌는지 확인하기 위해 입력한 배열을 다시 출력하였고, 정상적으로 입력이 완료되었음을 확인할 수 있다.
sth_1(첫번째 thread)은 입력값의 총합과 평균을 출력하고,
[사진3]
<br>
sth_2(두번째 thread)는 입력값을 높은 값부터 차례대로 내림차순 정렬하여 출력했다.
마지막으로, pthread_join을 이용하여 main thread는 child thread들이 종료될 때까지 기다리도록하게 했다.
따라서 thread의 종료 순서는 sth_1 -> sth_2 -> main thread 순이 되었다.
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment