본문 바로가기

프로그래밍 - 기본/CPP, Unity, Kotlin

쓰레드(thread)

스레드: CPU에서 실행되는 프로그램 단위

멀티 쓰레드:여러 개의 쓰레드로 구성된 프로그램

쓰레드 사용하는 이유:프로그램을 돌리는 시간을 단축시켜줌. 각각의 위치에서 할 일을 해낸 다음에 합치면 되기 때문임.

ex) 피보나치 수열

: 짝수와 홀수 부분을 담당하는 함수를 각각 나누어서 계산을 하게 한 다음 합쳐줌

 

#include<iostream>
#include<thread> //쓰레드를 사용하기 위해 포함시켜 줘야함
using namespace std;

void a(){
 cout<<"thread 1 run";
}

void b(){
 cout<<"thread 2 run";
}

void c(int n){
  int result = n;
}
int main(){
  thread one(a);
  thread two(b);
  //프로그램이 끝나면 끝남
  one.join();
  two.join();
  //프로그램이 끝나도 계속됨
  one.detach();
  two.detach();

  //함수에 전달인자를 넣고 싶을 때
  int number;
  cin>>number;
  thread three(c,number);
}