Upload
-
View
1.777
Download
1
Embed Size (px)
DESCRIPTION
KGC2009 강연
Citation preview
About Visual C++ 10
Microsoft Visual C++ MVP마이에트 엔터테인먼트
Server Programmer 최흥배
2003 년 1 월 ~
목차• Visual C++ 6 에서 Visual C++ 9…..
• Visual C++ 10 의 변화
• C++0x 의 신 기능
• Concurrency Runtime
1. Visual C++ 6 ~ 9
새로운 Visual Studio 시작…
• C++ 표준을 더욱 더 준수
• UI 완전 변경
• Managed C++
• Visual C++ 7
• 마이너 업그레이드 버전
• C++ 표준을 더욱 더 준수
• VC++ 버전 7(2002 와 동일 )
• 코드 분석 기능 추가 (SAL)
• 64 비트 컴파일 지원
• Managed C++ -> C++/CLI
• VC++ 버전 8
http://jacking.tistory.com/17
• C++/CLI, SAL 보완
• MFC UI 라이브러리 추가
• 멀티 스레드 디버깅 강화
• C++0x TR1 라이브러리 추가
• VC++ 버전 9
2002 부터 시작했던 Visual Studio 체계의 마지막
Visual Studio 2010( Visual C++ 10) 새로운 Visual Stuido 시대의 시작
뭐 바뀐게 있냐 ? -_-
2. Visual C++ 10 의 변화
Visual C++ Intel-lisense
• 목표는 256K Memory 의 16Bit DOS
• Intellisense 를 크게 어휘분석과 의미 해석으로 나눔
• 빠른 개발을 위해 ifdef 를 획기적으로 이용
• Intellisense 컴파일러를 FEACP 라고 부름 Front End Auto Complete Parser 의 약어
• 당시의 CPU 속도는 100MHz 정도 . 드롭 다운 윈도우를 100ms 이내에 . 초기화、멤버 오프셋 계산、 vtable 생성 생략 .
• 테스트와 점검은 악몽 Ifdef 때문에 많은 코드나 데이터의 의존성 문제
• Ifdef 지옥에 떨어졌음을 깨닫음
• 사람들은 Java 나 C# 의 Intellisense 기능을 원함 .
• FEACP 애서는 실현 불가능함
1992년
2009년
파이날 판타지 5 ( 슈퍼 패미콤 ) 파이날 판타지 13 (PS3)
“ 요즘 PC 의 속도와 용량이면 하나의 컴파일러로 C++ 의 코드 생성과 intel-lisense 양쪽 모두 가능한 새로운 intellisense 을 만들 수 있다 .!!!”
펜티엄 프로세스 66Mhz(1993 년 )
PC 의 메모리는 4 메가(1995)
인텔 i7 프로세스 4 core 3.33Ghz
PC 의 메모리는 4 기가
Dev 10 – Visual C++ 10
• Intellisense 에 가장 중요한 기능은 “정확성” Intellisense == 커맨드 라인 컴파일러
• 드롭 다운으로 올바를 멤버를 얻을 수 있는 것 이상
• 일부러 빌드를 하지 않아도 경고를 사전에 알 수 있다 . Intellisense 의 Parse 중에 발견된 에러는 진짜 에러 !!!
• 정확성에 의해 원시 코드의 리팩토링 등 가능
• 장래에는 유저가 접근할 수 있는 API 제공
• C++ 원키 코드에 대한 고정밀도의 정보에 접근할 수 있도록 할 예정
Visual C++ 10 IDE
VC++ 6
VC++ 9
VC++ 10
젤다의 전설 – 링크의 모험 ( 패미콤 ) 젤다의 전설 – 신들의 트라이포스 ( 슈퍼패미콤 )
젤다의 전설 – 시간의 오카리나 ( 닌텐도 64)
• IDE 를 WPF 및 닷넷 기술로 구현
• 응답성 , 확장성 , 정확성 강화 - 기존의 ncb 파일 제거 , SQL Compact 로 대체 - 대 규모 프로젝트도 문제 없음
• MSBuild 개선
• Deploy 설정 가능
DEMO
Visual C++ 10 IDE
멀티 모니터 지원
• 디버깅 하고 싶은 변수를 클릭하여 일종의 메모를 만듬 . 코멘트 추가 가능•I DE 내 , 외에 위치 가능• 디버깅이 끝나면 보이지 않음 .• 영구 저장된다 .
디버깅
소스 코드 창 확대 / 축소
추가된 MFC 라이브러리
CTaskDialog Restart Man-ager
- auto- static_assert- Rvalue Reference- lambda
3. C++ 0x 의 신 기능
• C++ 사용이 편해졌고 ,
• 언어의 표현력이 증대 되고 ,
• 성능 향상이 이루어졌습니다 .
C++0x 새로운 기능에 의해
auto
1. 변수 정의 때 명시적으로 type 을 지정하지 않아도 된다 .
2. auto 로 정의한 변수는 초기화할 때 type 이 결정 .
3. 컴파일 타임 때 type 이 결정 .
4. 템플릿 프로그래밍에 사용하면 코딩이 간편 . 5. 코드 가독성이 향상
예제 코드
auto NPCName = "KKamahui";cout << "NPC Name : " << NPCName << endl;
auto* CharInven = new CharacterInvenInfo();
typedef std::list<MCommand*> LIST_COMMAND;LIST_COMMAND::iterator iter = m_listCommand.begin();
auto iter = m_listCommand.begin();
DEMO
auto
static_assert
Assert 는 논리적인 오류 찾기 , 작업 결과 확인 , 처리해야 할 오류 조건 테스트 할때 사용
static_assert 는 컴파일 시점에서 실체화할 템플릿의 전제 조건을 조사할 때 사용
static_assert( “constant-expression”, “error-message” );
“constant-expression” - 검사할 조건 식“error-message” - 조건이 false 일 경우 출력할 error 메시지
예제 코드#include <iostream>using namespace std; const int MAX_LEVEL = 120; int main(){ static_assert( MAX_LEVEL <= 100, "Warring - MAX_LEVEL" ); return 0; }
예제 코드
template< typename T1, int StackSize >class MYSTACK{ static_assert( StackSize >= 10, "Stack Size Error" );public : MYSTACK() : data( new T[StackSize] ) { }……….};
DEMO
static_assert
Rvalue Reference
C++ 장점 중 하나인 성능은 향상 되었지만 ^^
C++ 단점 중 하나인 복잡함도 증가 -_-;
‘&’ 을 사용한 참조는 Lvalue Reference
int a = 10;int& refA = a;
‘&&’ 을 사용한 참조는 Rvalue Reference
int&& RrefA = a;
RValue Reference 의 의해
프로그램의 성능이 좋아지고
낭비가 없어짐 .
C++
C#, Java… C
Move seman-tics
왜 성능이 좋아질까요 ?
• move 생성자와 move 대입 연산자
• move 생성자와 move 대입 연산자는 암묵적으로 만들어지지 않는다 .
• 복사 생성자는 move 생성자보다 우선 한다 .
• 대입 연산자는 move 연산자보다 우선 한다 .
• 복사가 아닌 메모리 상에서 이동
• C++0x 의 STL 에는 Move semantics 가 적용
NEW NEW
move 생성자와 move 연산자 // Move 생성자 QuestInfo(QuestInfo&& quest) : Name(quest.Name), NameLen(quest.NameLen) { quest.Name = NULL; quest.NameLen = 0; } // Move 연산자 QuestInfo& operator=(QuestInfo&& quest) { if( this != &quest ) { delete Name; Name = quest.Name; NameLen = quest.NameLen; quest.Name = NULL; quest.NameLen = 0; } return *this; }
복사 생성자와 Move 생성자의 차이
// 복사 생성자
QuestInfo(const QuestInfo& quest) : Name(new char[quest.NameLen]), NameLen(quest.NameLen){ memcpy(Name, quest.Name, quest.NameLen);}
// Move 생성자
QuestInfo(QuestInfo&& quest) : Name(quest.Name), NameLen(quest.NameLen){ quest.Name = NULL; quest.NameLen = 0;}
VC++ 10 Beta 1 의 STL 의 vector
std::move
NPC npc2; NPC npc3;npc3 = npc2;
NPC npc7; NPC npc8;npc8 = std::move(npc7);
Move semsntice 에 따른 주의 점
int main(){
vector<int> v1;v1.push_back(10);v1.push_back(12);vector<int> v2 = std::move(v1);
cout << v1.size() << endl;cout << v2.size() << endl;return 0;
}
void inner(int& i){}template <typename T> void outer(T& t) {
inner(t);}int main(){
int a = 5;outer(a);outer(6);return 0;
}
컴파일 하면 outer(6) 에서 컴파일 에러가 발생“error C2664: 'outer' : cannot convert parameter 1 from 'int' to 'int &'“
Perfect forwarding
파라메터에 const 를 포함하는 함수를 재정의
예제 코드void inner(int& i){}template <typename T> void outer(T&& t) {
inner(t);}
int main(){
int a = 5;outer(a);outer(6);return 0;
}
DEMO
Rvalue Reference
lambda
간단하게 말하면 익명함수 . 람다 식 ( 람다 함수 )
C# 에서는 람다 식 덕분에 Linq 의 사용이 간편
C++ 에서는 STL 을 사용할 때와 템플릿을 사용할 때 편리함
예제 코드struct FindDieUser{
bool operator() (User& tUser) const { return tUser.IsDie(); }};
vector< User >::iterator Iter;Iter = find_if( Users.begin(), Users.end(), FindDieUser() );
예제 코드
vector< User >::iterator Iter;
Iter = find_if( Users.begin(), Users.end(), [](User& tUser) -> bool { return true == tUser.IsDie(); } );
람다 사용 방법
[]( 파라메터 ) { 식 }
int 값에 50 을 더한 후 반환하는 람다 함수
[](int x) { return x + 50; }
[]( 파라미터 ) { 식 }
파라미터와 반환 값이 같을 때
[](int x) { return x + 50; }
[]( 파라미터 ) -> 반환 값 자료형 { 식 }
[](int x) -> bool { return true; }
파라미터와 반환 값이 다를 때
[]( 파라미터 ) { 식 }
[](int x) { ++x; }
반환 값이 없을 때
클로져 사용
int TotalMoney1 = 0;
for_each( Moneys.begin(), Moneys.end(), [&TotalMoney1](int Money) {
TotalMoney1 += Money;}
);
클래스의 멤버 함수 호출
클래스 멤버 내의 람다 식은 해당 클래스에서는 friend 로 인식
람다 식에서 private 멤버의 접근도 가능
예제 코드
void AllSend() const{ for_each( SendPackets.begin(), SendPackets.end(), [this](int i){ Send(i); } ); }
DEMO
lambda
Language FeaturePro-posal
Available in GCC 4.4?
Rvalue references N2118 Yes Rvalue references for *this N2439 NoInitialization of class objects by rvalues N1610 YesVariadic templates N2242 Yes Extending variadic template template pa-rameters N2555 Yes
Initializer lists N2672 YesStatic assertions N1720 Yesauto-typed variables N1984 Yes Multi-declarator auto N1737 Yes Removal of auto as a storage-class specifier N2546 Yes New function declarator syntax N2541 YesLambda expressions and closures N2550 No Constness of lambda functions N2658 NoDeclared type of an expression N2343 YesRight angle brackets N1757 YesDefault template arguments for function tem-plates DR226 Yes
Solving the SFINAE problem for expressions DR339 YesTemplate aliases N2258 NoExtern templates N1987 YesNull pointer constant N2431 NoStrongly-typed enums N2347 YesForward declarations for enums N2764 NoGeneralized attributes N2761 NoGeneralized constant expressions N2235 NoAlignment support N2341 NoDelegating constructors N1986 NoInheriting constructors N2540 NoExplicit conversion operators N2437 NoNew character types N2249 YesUnicode string literals N2442 YesRaw string literals N2442 NoUniversal character name literals N2170 NoExtensible literals N2765 NoStandard Layout Types N2342 NoDefaulted and deleted functions N2346 Yes
Extended friend declara-tions N179
1No
Extending sizeof N2253
YesInline namespaces N253
5Yes
Unrestricted unions N2544
NoLocal and unnamed types as template arguments N265
7No
Minimal support for garbage collection and reachability-based leak detection
N2670
No
Concepts N2773
NoConcurrency
Sequence points N2239
NoAtomic operations N242
7No
Strong Compare and Ex-change N274
8No
Bidirectional Fences N2752
NoMemory model N242
9No
Data-dependency ordering: atomics and memory model N266
4No
Propagating exceptions N2179
YesAbandoning a process and at_quick_exit N244
0No
Allow atomics use in signal handlers N254
7No
Thread-local storage N2659
NoDynamic initialization and destruction with concur-rency
N2660
No
C99 Features in C++0x__func__ predefined identi-fier N234
0Yes
C99 preprocessor N1653
Yeslong long N181
1Yes
Extended integral types N1988
No
4. Concurrency Run-time
CPU 의 성능 향상은
Ghz 에서Multi Core로CPU 코어 하이퍼 스레드 스레드 GHz
Pentium 4 1 〇 2 3.4
Core2 Duo 2 X 2 3.0
Core i7 4 〇 8 3.2
무어의 법칙은 불변이지만…
소프트웨어 Free Lunch 는 끝났다
멀티 스레드 ? 멀티코어 ? 그거 먹는건가요 ? 우걱우걱
이상 현실
• Parallel Patterns Library
Concurrency Runtime 병행 런타임
• Synchronization Data Structures
• Asynchronous Agents Library
병렬 패턴 라이브러리 ( PPL )
PPL 의 세 가지 features
• Task Parallelism
• Parallel algorithms
• Parallel containers and objects
Task Parallelism
• 실제적인 task 의 실행은 task_group 에서 한다 .
• unstructured_task_group(task_group) 와 structured_task_group 로 나누어진다 .
• task_group : 스레드 세이프 structured_task_group : 스레드 세이프 하지 않음 .
Thread Atask_group1.run( task2)
Thread Btask_group1.run( task3)
task_group1.run( task1)
Thread Astructured_task_group1.run( task2)
structured_task_group1.run( task1)
Main Thread
Main Thread
초 간단 !!! task 사용 방법1. ppl.h 파일을 포함합니다 .
#include <ppl.h>
2. Concurrency Runtime 의 네임 스페이를 선언합니다 . using namespace Concurrency;
3. 태스크 그룹을 정의합니다 .structured_task_group structured_tasks;
4. 태스크를 정의합니다 . auto structured_task1 = make_task([&] { Plus(arraynum1, true); } );
5. 태스크를 태스크 그룹에 추가한 후 실행합니다 . structured_tasks.run( structured_task1 );
6. 태스크 그룹에 있는 태스크가 완료될 때까지 기다립니다 . structured_tasks.wait();
DEMO
parallel_task
Parallel Algorithms
• 데이터 컬렉션을 대상으로 쉽게 병렬 작업을 할 수 있게 해주는 알고리즘들 .
• C++ STL 에서 제공하는 알고리즘과 비슷한 모양과 사용법 .
• paeallel_for, parallel_for_each, parallel_invoke 가 구현되어 있음 .
parallel_accumulate, parallel_partial_sum 은 Beta 1 에서는 아직 미 구현 .
parallel_for
• for 문을 병렬화 .
• for 문과 사용 방법이 흡사하여 쉽게 변환 .
• step 값을 지정하는 버전과 지정하지 않는 버전 두 개가 있음 ( 지정하지 않으면 1).
• index 조사는 ‘ <‘ 만 지원 .
초 간단 !!! parallel_for 사용 법1. ppl.h 파일을 포함합니다 .
#include <ppl.h>
2. Concurrency Runtime 의 네임 스페이를 선언합니다 . using namespace Concurrency;
3. parallel_for 에서 호출할 함수 정의
4. parallel_for 에서 사용할 data set 정의 .
5. parallel_for 사용 .
parallel_for_each
• STL 의 for_each 알고리즘을 병렬화 .
• for_each 와 사용 방법이 같음 .
초 간단 !!! parallel_for_each 사용 법1. ppl.h 파일을 포함합니다 .
#include <ppl.h>
2. Concurrency Runtime 의 네임 스페이를 선언합니다 . using namespace Concurrency;
3. parallel_for_each 에서 호출할 함수 정의
4. parallel_for_each 에서 사용할 data set 정의 .
5. parallel_for_each 사용 .
parallel_invoke
• 병렬로 일련의 태스크 실행 .
• 동시 실행할 복수의 독립된 태스크를 실행할 때 좋음 .
• task_group 과 비슷하나 사용방법은 더 쉬움그러나 최대 10 개의 태스크만 병렬 작업이 가능하다 .
초 간단 !!! parallel_invoke 사용 법1. ppl.h 파일을 포함합니다 .
#include <ppl.h>
2. Concurrency Runtime 의 네임 스페이를 선언합니다 . using namespace Concurrency;
3. 태스크 정의
4. parallel_invoke 사용 .
parallel objects - combinable
• 스레드 세이프한 오브젝트 .
• 계산 실행한 후 최종 결과에 그 계산 결과를 통합하는 재 사용 가능한 로컬 스트리지 제공 .
• 복수의 스레드 또는 채스크 간에 공유 리소스가 있는 경우 편리 .
• lock-free thread-local sub-computations during parallel algo-rithms
• combinable 클래스에 사용할 데이터는 기본 생성자와 복사 생성자를 가지고 있어야 한다 .
• Win32 API의 thread local storage와 비슷 .
• combine, combinable_each 제공
예제 코드#include <algorithm>#include <iostream> using namespace std;using namespace Concurrency; int main(){ vector<int> values(10); int n = 0; generate(values.begin(), values.end(), [&]
{ return ++n; } ); combinable<int> sums; parallel_for_each(values.begin(), values.end(),
[&](int n) { sums.local() += n; });
int result = sums.combine([](int left, int right) { return left + right; }); cout << "The sum of " << values.front() << " to " << values.back() << " is " << result << ".";}
예제 코드using namespace std;using namespace Concurrency; int main(){ vector<int> values(10); int n = 0; generate(values.begin(), values.end(), [&]
{ return ++n; } ); combinable<list<int>> odds; parallel_for_each(values.begin(), values.end(),
[&](int n) { if (n % 2 == 1) odds.local().push_back(n); });
list<int> result; odds.combine_each([&](list<int>& local) { local.sort(less<int>()); result.merge(local, less<int>()); }); cout << "The odd elements of the vector are:"; for_each(result.begin(), result.end(), [](int n) { cout << ' ' << n; });}
concurrent containers
• 병렬 환경에서 스레드 세이프하게 데이터를 저장 .
• concurrent_queue, concurrent_vector, concurrent_hash_map.
• Beta1 에서는 아직 미 구현 .
MSDNhttp://msdn.microsoft.com/en-us/library/dd504870(VS.100).aspx
Visual C++ Team 블로그http://blogs.msdn.com/vcblog/default.aspx
VSTS 2010 스터디 블로그http://vsts2010.net
Parallel Programming in Native Codehttp://blogs.msdn.com/nativeconcurrency/default.aspx
본인 블로그http://jacking.tistory.com/