본문 바로가기
VisualStudio.C++.C#/C . C++

C++ std::thread 클래스 이용한 스레드. 클래스멤버함수를 스레드로 실행시키는 방법.

by i.got.it 2016. 1. 16.

개요

std::thread 클래스 개요및 스레드 생성 코드 예, 클래스 멤버함수를 스레드로 실행시키는 방법 .
 
C++11부터 std::thread 클래스 로 스레드 생성 가능하며, VC++ (Visual Studio 2012 이후 )에서도 사용가능하다.
VC++에서 통상적인 스레드 생성하는 AfxBeginThread 방식(상세보기 -> http://igotit.tistory.com/211 ) 보다 많이 편하다.
 
헤더 : <thread>
 
 
thread 클래스
프로그램내의 스레드 생성 관리.
 
설명
 

You can use a thread object to observe and manage a thread of execution within an application.A thread object that's created by using the default constructor is not associated with any thread of execution.A thread object that's constructed by using a callable object creates a new thread of execution and calls the callable object in that thread.Thread objects can be moved but not copied.Therefore, a thread of execution can be associated with only one thread object.
Every thread of execution has a unique identifier of type thread::id.The function this_thread::get_id returns the identifier of the calling thread.The member function thread::get_id returns the identifier of the thread that's managed by a thread object.For a default-constructed thread object, the thread::get_id method returns an object that has a value that's the same for all default-constructed thread objects and different from the value that's returned by this_thread::get_id for any thread of execution that could be joined at the time of the call.
 
NameDescription
thread::id 클래스 Uniquely identifies the associated thread.
NameDescription
thread::thread 생성자 Constructs a thread object.
NameDescription
thread::detach 메서드 Detaches the associated thread from the thread object.
thread::get_id 메서드 Returns the unique identifier of the associated thread.
thread::hardware_concurrency 메서드 Static.Returns an estimate of the number of hardware thread contexts.
thread::join 메서드 Blocks until the associated thread completes.
thread::joinable 메서드 Specifies whether the associated thread is joinable.
thread::native_handle 메서드 Returns the implementation-specific type that represents the thread handle.
thread::swap 메서드 Swaps the object state with a specified thread object.
NameDescription
thread::operator= 연산자 Associates a thread with the current thread object.

요구 사항

Header: thread
Namespace: std


thread 생성자.
Constructs a thread object.
구문
 

 
복사
thread() _NOEXCEPT; template<class Fn, class... Args> explicit thread(Fn&& F, Args&&... A); thread(thread&& Other) _NOEXCEPT;
FAn application-defined function to be executed by the thread.
AA list of arguments to be passed to F.
OtherAn existing thread object.
설명
 

The first constructor constructs an object that's not associated with a thread of execution.The value that's returned by a call to get_id for the constructed object is thread::id().
The second constructor constructs an object that's associated with a new thread of execution and executes the pseudo-function INVOKE that's defined in <functional>.If not enough resources are available to start a new thread, the function throws a system_error object that has an error code of resource_unavailable_try_again.If the call to F terminates with an uncaught exception, terminate is called.
The third constructor constructs an object that's associated with the thread that's associated with Other.Other is then set to a default-constructed state.

 

1. std::thread 이용 스레드 생성 코드 예.

스레드 생성

 
std::thread myThread(func,this,1,2.f) ;
 
혹은 std::thread* pThread = new std::thread(func,this,1,2.f); // 동적 생성하는 경우.
 
설명 :  함수 func 를 스레드로 생성하며 동시에 3개의 인자 this, 1, 2.f를 전달하는 예.  
비교 : AfxBeginThread 로 생성시키는 경우 인자는 1개만 가능했으나 std:thread에서는 인자 수량 복수개 가능. 
 
스레드로 실행시킬 함수 예.
위 스레드 생성자에 인자로 전달하여 스레드로 생성시킬 함수 예.
class 의 staic 함수나 전역함수만 가능하며 클래스멤버함수 불가.
void func(LPVOID lParam, int i, float f)
{
...
}
 
스레드 실행 끝날때까지 대기.
 
std::thread myThread(func,this,1,2.f) ; // 스레드 생성
myThread.join(); // 상기 스레드 종료시 까지 여기서 대기하게됨.
 

 

2. 클래스 멤버함수를 스레드로 실행시키는 방법. - 람다 이용.

 

앞의 예와 같이 함수를 직접 생성자에 전달하는 방식인 경우 클래스의 static함수나 전역함수만 전달가능하다.


클래스의 멤버함수를 전달하여 스레드로 실행시키기 위해서는 람다 로 전달하는 방식으로 가능해진다. 


예. 클래스의 멤버함수가   void class::func() {} 로 정의되어있는데, 이 함수를 람다식으로 아래 처럼 하면
클래스 멤버함수가 스레드로 실행된다.


std::thread( [&] () { func(); } );



검정색이 람다 임.

 

 

 

 

 

 

 

상위 정리 

Visual Studio/VC++/C/C# 활용정리 -> http://igotit.tistory.com/11

 

Visual Studio , Visual C++ 활용 정리.

Visual Studio C++ 활용 Visual Studio Visual C++ / C# 1.설치, 설정  주제  비고.  Visual Studio 2010 설치.  Visual Studio 2013 (Community)무료 설치.  Visaul Studio 2015 (Community)무료 설치...

igotit.tistory.com

 

 

 

 


첫 등록 : 2016.01.16

최종 수정 : 

단축 주소 : https://igotit.tistory.com/559


 

 

댓글



 

비트코인




암호화폐       외환/나스닥/골드       암호화폐/외환/나스닥/골드 암호화폐/외환/나스닥/골드   암호화폐/외환/나스닥/골드
     
현물 |선물 인버스 |선물 USDT       전략매니저(카피트레이딩)     롤오버 이자 없는 스왑프리계좌
( 스왑프리 암호화폐도 거래 가능 )    
MT4, MT5 , cTrader 모두 지원     FTMO 계좌 매매운용. MT4,MT5