엔지니어 동행하기

Concurrency & Parallel Programming과 std::thread 설명 본문

Modern C++/Concurrency & Parallel

Concurrency & Parallel Programming과 std::thread 설명

엔지니어 설리번 2022. 8. 7. 10:38
반응형
처음 접하는 경우 헷갈릴 수 있는 개념으로, Concurrency Programming과 Parallel Programming의 차이에 대해 확실히 구분하고 갈 필요가 있습니다. 또한 이러한 프로그래밍 방식을 사용하기 위해 기초적으로 알아야 하는 std::thread에 대해 설명드리겠습니다. 

 

Single threaded process  VS  Multi threaded process

Thread에 관한 기본적인 설명은 다음 블로그를 참고하면 됩니다.

https://goodgid.github.io/What-is-Thread/

 

쓰레드(Thread)란 무엇인가?

Index

goodgid.github.io

기본적으로 Process에는 Main Thread가 존재하며 이외에 다른 Thread가 없을 경우 Single threaded process라 할 수 있습니다. 반면 다른 thread가 존재한다면 Multi threaded process가 됩니다.

Single threaded vs Multi threaded

Multi threaded process에서 각 Thread는 Registers와 Stack은 독립적으로 갖고 있는 반면, Heap/ Static/ Code는 공유하고 있음을 알 수 있습니다. (Multi thread일 때 발생하는 문제인 Data Race는 해당 자원을 공유해서 생깁니다. )

따라서 각 Thread에서는 독립적인 함수 호출을 통해 독립적인 실행 흐름을 만들 수 있으며, 공유 자원을 통해 커널 도움 없이 Thread 간 통신이 가능합니다. 

 

Concurrency Programming  VS  Parallel Programming

간단히 두 개념의 차이를 비교해 설명하면 다음과 같습니다.

-  Concurrency Programming : 논리적인 개념으로 싱글 코어에서 Multi thread를 동작시키기 위한 방법입니다.

-  Parallel Programming : 물리적으로 멀티 코어에서 Multi thread를 동작시키는 방법입니다. 

물론 멀티코어에서도 Concurrency Programming이 가능합니다. 정리하면, 한정된 Core에 Context Switching을 하면서 Multi thread를 처리하는지 여부로 구분할 수 있습니다.

 

std::thread

std::thread는 Concurrency와 Paralle의 기본이 되는 개념으로 C++ 11부터 사용이 가능합니다. 

1) Constructor

thread() noexcept;                                               // stack에 thread객체를 생성하고 실질적인 실행 흐름은 만들지 않음

thread( thread&& other ) noexcept;                     // move constructor

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );     // Function을 넘겨주고 실질적인 실행 흐름을 만듦

thread( const thread& ) = delete;                        // copy constructor 정의가 없기 때문에 R value로 바꿔줘야 함.

2) Operations

-  join : 현재 thread를 block하고 target thread의 실행이 끝날 때까지 기다립니다.

-  detach : thread object와 실행 흐름을 분리합니다. 


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

 

반응형
Comments