Rylah's Study & Daily Life
01. Thread 본문
지금까지 배운 C++는 Single Thread 프로그램이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
#include <iostream>
class Knight
{
public:
Knight() : _hp{ 100 }
{
}
~Knight()
{
}
void PrintKnightHp()
{
std::cout << _hp << std::endl;
}
private:
int _hp;
};
void printMeow()
{
std::cout << "Meow~" << std::endl;
}
int main()
{
int a = 50;
int b = 70;
int c = a * b;
std::cout << "A : " << a << std::endl;
std::cout << "B : " << b << std::endl;
std::cout << "C : " << c << std::endl;
printMeow();
Knight k1; // Constructor;
k1.PrintKnightHp();
}
|
cs |

이러한 코드의 흐름은 다 알것이다.
변수 a를 만들고 b를 만들고 c를 a와 b를 곱해서 만들고
a b c를 출력하고
함수 하나를 출력하고
객체를 하나 생성하고
객체의 멤버 함수를 출력하는 순서대로 이뤄진다.
이런게 싱글 스레드 프로그램이다.
앞으로 이용할 멀티쓰레드 프로그램은 프로그램의 수만큼 스택, 스레드가 존재한다.
code, data |
stack |
thread |
싱글스레드는 단순하게 이런 구조지만
Code , data~ , Heap~~~~~~~~~~~~~~~ | |||||||||
stack thread |
stack thread |
stack thread |
stack thread |
stack thread |
stack thread |
stack thread |
stack thread |
stack thread |
stack thread |
이러한 방식의 프로그램이 멀티 쓰레드 프로그램의 방식이다.
물론 스택이나 쓰레드는 더 많이 있을 수 있다.
조금 그림을 바꾸면

싱글스레드에서는
이런식으로 스택 영역에서 하나씩 스택프레임이 쌓이고 해제 되는 과정이 반복되고
Heap 영역에 동적할당을 하기도하고 해제하기도 한다.
쓰레드도 이런 흐름으로 동작했는데
멀티쓰레드에서는 메모리가 이런 느낌이다.

간략화 시키고 대략적인 그림이라 틀릴수 있지만
다른 스택프레임이 있고 거기에 쓰레드랑 그런게 쌓이고 동적할당인 힙 영역은 공유하는 것이다.
C++에서는 std::thread에서 생성할 수 있다.
https://en.cppreference.com/w/cpp/thread/thread
std::thread - cppreference.com
class thread; (since C++11) The class thread represents a single thread of execution. Threads allow multiple functions to execute concurrently. Threads begin execution immediately upon construction of the associated thread object (pending any OS scheduling
en.cppreference.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#include <iostream>
#include <thread>
void function()
{
int a = 0;
std::cout << "print" << std::endl;
}
int main()
{
std::cout << "Do Program!!!" << std::endl;
std::thread t1(function);
std::thread t2(function);
t1.join();
t2.join();
std::cout << "process end" << std::endl;
return 0;
}
|
cs |


그림이 이상하게 그려지긴했는데 대략적으로 이런식으로 쓰레드들이 따로 실행되는 것을 볼 수 있다.
이 뿐만 아니라 람다식도 쓰레드에서 써먹을수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#include <iostream>
#include <thread>
void function()
{
int print = 0;
std::cout << "print" << std::endl;
}
int main()
{
std::cout << "Do Program!!!" << std::endl;
std::thread t1(function);
std::thread t2(function);
std::thread t3([] {
int a = 0;
std::cout << "lambda thread" << std::endl;
});
t1.join();
t2.join();
t3.join();
std::cout << "process end" << std::endl;
return 0;
}
|
cs |

'Study > C++' 카테고리의 다른 글
Modern C++ : 03. C++ Build : Dynamic Library (Shared Library) (0) | 2022.03.29 |
---|---|
Modern C++ : 03. C++ Build : Static Library (0) | 2022.03.29 |
rax eax (0) | 2022.03.24 |
.bss .data .rodata (0) | 2022.03.23 |
날짜 계산 (0) | 2022.03.22 |