[명품 운영체제] 4장 복합문제

2024. 4. 3. 19:31·명품 운영체제

복합문제 1번 소스코드 prac4_1.c

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void* runner(void *param); // 스레드로 작동할 코드(함수)
int sum[4]={0}; // 각 스레드 결과값 
int totalSum=0; // 스레드 결과의 총합
int j=0; // 스레드 만들 때마다 ++

int main(){
        pthread_t tid1; // 스레드의 id를 저장할 정수형 변수
        pthread_t tid2;
        pthread_t tid3;
        pthread_t tid4;
        pthread_attr_t attr; // 스레드 정보를 담을 구조체 

        pthread_attr_init(&attr); //디폴트 값으로 attr 초기화
        pthread_create(&tid1, &attr, runner, "1"); // runner 스레드 생성
        pthread_create(&tid2, &attr, runner, "10001");
        pthread_create(&tid3, &attr, runner, "20001");
        pthread_create(&tid4, &attr, runner, "30001");

        pthread_join(tid1, NULL); // tid 번호의 스레드 종료를 기다림
        pthread_join(tid2, NULL);
        pthread_join(tid3, NULL);
        pthread_join(tid4, NULL);

        for(int i=0; i<4; i++){
                totalSum+=sum[i];
        }

        printf("1에서 40000까지 4개의 스레드가 계산한 총 합은 %d\n", totalSum);
}

void* runner(void *param){ // param에 문자열 변수 전달받음
    int to= atoi(param); // 문자열을 정수형으로 
    int tmp_sum=0; // 반복문에서 쓸 임시 합

    for(int i=to; i<to+10000; i++){ // to에서 to+10000까지
        tmp_sum+=i;
    }
    sum[j]=tmp_sum; // 임시합을 스레드 순서대로 넣기 
    j++;
}

 

컴파일 및 실행결과 

복합문제 2번 소스코드 prac4_2.c

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void* runner(void *param); // 스레드로 작동할 코드(함수)
int sum=0;

int main(){
        pthread_t tid1; // 스레드의 id를 저장할 정수형 변수
        pthread_t tid2;
        pthread_t tid3;
        pthread_t tid4;
        pthread_attr_t attr; // 스레드 정보를 담을 구조체 

        pthread_attr_init(&attr); //디폴트 값으로 attr 초기화
        pthread_create(&tid1, &attr, runner, "1"); // runner 스레드 생성
        pthread_create(&tid2, &attr, runner, "10001");
        pthread_create(&tid3, &attr, runner, "20001");
        pthread_create(&tid4, &attr, runner, "30001");

        pthread_join(tid1, NULL); // tid 번호의 스레드 종료를 기다림
        pthread_join(tid2, NULL);
        pthread_join(tid3, NULL);
        pthread_join(tid4, NULL);


        printf("1에서 40000까지 4개의 스레드가 합친 sum 변수의 값은 %d\n", sum);
}

void* runner(void *param){ // param에 문자열 변수 전달받음
    int to= atoi(param); // 문자열을 정수형으로 

    for(int i=to; i<to+10000; i++){ // to에서 to+10000까지
        sum+=i;
    }
}

실행결과

 

위 코드를 실행할 때마다 다른 값이 나오는 이유 :

스레드가 동시에 병렬로 실행되기 때문에 

공유데이터에 동시에 접근하여 예상치 못한 값이 발생하였다.

 

'명품 운영체제' 카테고리의 다른 글

[명품 운영체제] 8장 복합문제  (0) 2024.05.13
[운영체제] 생산자 소비자  (2) 2024.04.18
[운영체제] 세마포에 대해서  (0) 2024.04.18
뮤텍스와 스핀락  (2) 2024.04.18
6. 스레드 동기화  (0) 2024.04.18
'명품 운영체제' 카테고리의 다른 글
  • [운영체제] 생산자 소비자
  • [운영체제] 세마포에 대해서
  • 뮤텍스와 스핀락
  • 6. 스레드 동기화
코딩 못하는 감자
코딩 못하는 감자
  • 코딩 못하는 감자
    코딩 못하는 감자의 기록
    코딩 못하는 감자
  • 전체
    오늘
    어제
    • 분류 전체보기 (91)
      • Kubernetes (10)
      • Github Action (1)
      • Docker, Container (3)
      • Springboot (26)
      • Baekjoon (4)
      • 명품 운영체제 (9)
      • 데이터베이스 (2)
      • JSP (3)
      • 안드로이드프로그래밍 (1)
      • 미니프로젝트 (1)
      • 용어정리 (0)
      • 소프트웨어공학 (3)
      • 운영체제 (2)
      • Flutter (0)
      • Git (1)
      • HTTP (0)
      • RAG (1)
      • Database (2)
      • FastAPI (1)
      • Elasticsearch (7)
      • Redis (0)
      • JPA (5)
      • Linux (1)
      • MCP (1)
  • 블로그 메뉴

    • 홈
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    엘라스틱서치 인덱스 복사
    SpringBoot
    fuzziness
    엘라스틱서치 인덱스
    응답 로그
    elasticsearch ngram
    elasticsearch analyzer
    Dockerfile
    elasticsearch 커스텀분석기
    mcp #model context protocol #claude desktop #mcp claude연동 #claude 파일 시스템 연동
  • hELLO· Designed By정상우.v4.10.3
코딩 못하는 감자
[명품 운영체제] 4장 복합문제
상단으로

티스토리툴바