SlideShare a Scribd company logo
1 of 51
Lambda Expression
& Concurrency API
김명신 부장
Principal Technical Evangelist
완전 친절한
Lambda
Expression
완전 불친절한
Concurrency API
완전 간단한
실천적 접근
Alonzo Church
[lambda-capture] { body }
[lambda-capture] (params) { body }
[lambda-capture] (params) -> ret { body }
[lambda-capture] (params) mutable exception attribute -> ret { body }
[lambda-capture] (params) mutable exception attribute -> ret { body }
int x = 10, y = 20;
[] {}; // capture 하지 않음
[x](int arg) { return x;}; // value(Copy) capture x
[=] { return x;}; // value(Copy) capture all
[&] { return y;}; // reference capture all
[&, x] { return y;}; // reference capture all except x
[=, &y] { return x;}; // value(Copy) capture all except y
[this] { return this->something;}; // this capture
[=, x] {}; // error
[&, &x] {}; // error
[=, this] {}; // error
[x, x] {}; // error
Capture default =, &를 하였더라도 body에서
사용하지 않았다면 capture는 일어나지 않음
[lambda-capture] (params) mutable exception attribute -> ret { body }
[](int &factor, int total) {
if (factor == 0) return total;
return factor;
};
[](float &factor, double total) -> double {
if (factor == 0) return total;
return factor;
};
[lambda-capture] (params) mutable exception attribute -> ret { body }
[x]() mutable { return ++x; };
[x]() throw() {
if (x == 0)
throw std::bad_exception(); // warning
};
cout << typeid([] {}).name() << endl; class <lambda_04197a50f746795ff56aab1f0f0bfa52>
int x = 10, y = 20;
[x] { return ++x; };
[x, &] { return x + y; };
[=, x] { return x; };
[]() noexcept { throw bad_exception(); };
[x]() mutable { return ++x; };
[&, x] { return x + y; };
[=] { return ++x; };
[] { throw bad_exception(); };
int x = 1;
cout << x << endl;
[x]() mutable { ++x; }();
cout << x << endl;
[&x]() { ++x; }();
cout << x << endl;
1
1
2
1
2
2
void fa(int x, function<void(void)> f) { ++x; f(); }
void fb(int x, function<void(int)> f) { ++x; f(x); }
void fc(int &x, function<void(void)> f) { ++x; f(); }
int x = 1;
fa(x, [x] { cout << x << endl; });
fb(x, [](int x) { cout << x << endl; });
fc(x, [&x] { cout << x << endl; });
struct Less
{
bool operator()(const int &left, const int &right) const
{
return left < right;
}
};
sort(begin(v), end(v), Less());
sort(begin(v), end(v), [](int x, int y) { return x < y; });
template<typename T>
class Less_than {
const T val;
public:
Less_than(const T& v) : val(v) {};
bool operator()(const T& x) const { return x < val; };
};
int num = 5;
Less_than<int> less5{ num };
auto diff = count_if(begin(v), end(v), less5);
auto diff = count_if(begin(v), end(v), [num](int value) { return value < num; });
// return lambda function
auto addtwointegers = [](int x) -> function<int(int)> {
return [=](int y) { return x + y; };
};
// lambda function as parameter
auto higherorder = [](const function<int(int)>& f, int z) {
return f(z) * 2;
};
auto answer = higherorder(addtwointegers(7), 8);
WNDCLASSEX wcex;
wcex.lpfnWndProc= [](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) ->
LRESULT {
switch (message) {
case WM_COMMAND:
EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL {
char szText[256];
GetWindowTextA(hwnd, szText, 256);
cout << szText << endl;
return TRUE;
}, 0);
HANDLE hT = CreateThread(NULL, 0, [](LPVOID lpThreadParameter) -> DWORD {
for (int i = 0; i < 1000; i++) {
this_thread::sleep_for(milliseconds{ 10 });
cout << i << endl;
}
return 0;
}, NULL, 0, NULL);
sizeof(int) = ?
1=sizeof(char)<=sizeof(short)<=sizeof(int)<=sizeof(long)<=sizeof(long long)
1<=sizeof(bool)<=sizeof(long)
sizeof(char)<=sizeof(wchar_t)<=sizeof(long)
sizeof(float)<=sizeof(double)<=sizeof(long double)
sizeof(N)=sizeof(signed N)=sizeof(unsigned N)
void f2(const int arg) { cout << "f2(" << arg << ")" << endl; }
void f3(const int arg, int *pResult) {
cout << "f3(" << arg << ")" << endl; *pResult = arg; }
int _tmain(int argc, _TCHAR* argv [])
{
thread t1([] { cout << "f1()" << endl; }); // lambda expression
thread t2(f2, 10); // passing argument
int result;
thread t3(f3, 10, &result); // how to get the result
t1.join();t2.join(); t3.join(); // barrier
cout << "Result = " << result << endl;
}
void f2(const int arg) { cout << "f2(" << arg << ")" << endl; }
void f3(const int arg, int *pResult) {
cout << "f3(" << arg << ")" << endl; *pResult = arg;
}
int f4(const int arg) {
cout << "f4(" << arg << ")" << endl; return arg;
}
int _tmain(int argc, _TCHAR* argv [])
{
auto t1 = async([] { cout << "f1()" << endl; }); // lambda expression
auto t2 = async(f2, 10); // passing argument
int result;
auto t3 = async(f3, 10, &result); // how to get the result
t1.get(); t2.get(); t3.get();
auto t4 = async(f4, 10); // return value
result = t4.get();
cout << "Result = " << result << endl;
}
get()
set_value()
set_exception()
int sum(int n) { return n == 1 ? 1 : n + sum(n - 1); }
....
using value_type = int;
promise<value_type> pr;
future<value_type> fu = pr.get_future();
int num = 10;
pr.set_value(sum(num));
//pr.set_exception(make_exception_ptr(exception("error")));
try {
value_type result = fu.get();
cout << result;
} catch (exception &ex) {
cout << ex.what() << endl;
}
using value_type = int;
promise<value_type> pr;
future<value_type> fu = pr.get_future();
int num = 10;
thread t{ [&,num] {
pr.set_value(sum(num));
//pr.set_exception(make_exception_ptr(exception("error")));
}};
try {
value_type result = fu.get();
cout << result;
} catch (exception &ex) {
cout << ex.what() << endl;
}
t.join();
get()
set_value(x)
set_exception(x)
return x;
throw x;
try {
pr.set_value(tsk(args));
} catch (...) {pr.set_exception(current_exception()); }
using value_type = int;
packaged_task<value_type(int)> pt{ sum };
future<value_type> fu = pt.get_future();
int num = 10;
pt(num);
try {
value_type result = fu.get();
cout << result;
} catch (exception &ex) {
cout << ex.what() << endl;
}
using value_type = int;
packaged_task<value_type(int)> pt{ sum };
future<value_type> fu = pt.get_future();
int num = 10;
thread t{ move(pt), 10 };
try {
value_type result = fu.get();
cout << result;
} catch (exception &ex) {
cout << ex.what() << endl;
}
t.join();
void producer()
{
int x = 1;
while (x)
{
packaged_task<int()> pt{ bind(sum, x++) };
{
unique_lock<mutex> ul(mtx);
q.push_back(move(pt));
}
cond.notify_one();
this_thread::sleep_for(milliseconds{ 100 });
}
}
void consumer()
{
while (true)
{
packaged_task<int(void)> pt;
{
unique_lock<mutex> ul(mtx);
cond.wait(ul, [] {return !q.empty(); });
pt = move(q.front());
}
pt();
cout << pt.get_future().get() << endl;
q.pop_front();
}
}
int sum(int n) { return n == 1 ? 1 : n + sum(n - 1); }
deque<packaged_task<int()> > q;
mutex mtx;
condition_variable cond;
using value_type = int;
future<value_type> fu = async(sum, 10);
try {
value_type result = fu.get();
cout << result;
} catch (exception &ex) {
cout << ex.what() << endl;
}
C++ Lambda and concurrency
C++ Lambda and concurrency
C++ Lambda and concurrency
C++ Lambda and concurrency

More Related Content

What's hot

Travel management
Travel managementTravel management
Travel management
1Parimal2
 

What's hot (20)

C++ Programming - 2nd Study
C++ Programming - 2nd StudyC++ Programming - 2nd Study
C++ Programming - 2nd Study
 
C++ Programming - 1st Study
C++ Programming - 1st StudyC++ Programming - 1st Study
C++ Programming - 1st Study
 
C++ L06-Pointers
C++ L06-PointersC++ L06-Pointers
C++ L06-Pointers
 
C++ Programming - 4th Study
C++ Programming - 4th StudyC++ Programming - 4th Study
C++ Programming - 4th Study
 
Go a crash course
Go   a crash courseGo   a crash course
Go a crash course
 
C++ L01-Variables
C++ L01-VariablesC++ L01-Variables
C++ L01-Variables
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and C
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
 
C++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+OperatorsC++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+Operators
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency API
 
Encrypt all transports
Encrypt all transportsEncrypt all transports
Encrypt all transports
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)
 
Rich and Snappy Apps (No Scaling Required)
Rich and Snappy Apps (No Scaling Required)Rich and Snappy Apps (No Scaling Required)
Rich and Snappy Apps (No Scaling Required)
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
Singly Linked List
Singly Linked ListSingly Linked List
Singly Linked List
 
c programming
c programmingc programming
c programming
 
Whispered secrets
Whispered secretsWhispered secrets
Whispered secrets
 
c programming
c programmingc programming
c programming
 
Travel management
Travel managementTravel management
Travel management
 

Similar to C++ Lambda and concurrency

Project_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_endsProject_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_ends
? ?
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
Takayuki Goto
 
I wrote the following change it to having a header, main and cpp fi.pdf
I wrote the following change it to having a header, main and cpp fi.pdfI wrote the following change it to having a header, main and cpp fi.pdf
I wrote the following change it to having a header, main and cpp fi.pdf
rishteygallery
 

Similar to C++ Lambda and concurrency (20)

Blocks+gcd入門
Blocks+gcd入門Blocks+gcd入門
Blocks+gcd入門
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
Go vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoFGo vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoF
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Project_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_endsProject_Euler_No_104_Pandigital_Fibonacci_ends
Project_Euler_No_104_Pandigital_Fibonacci_ends
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
include.docx
include.docxinclude.docx
include.docx
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methods
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For Google
 
Add an interactive command line to your C++ application
Add an interactive command line to your C++ applicationAdd an interactive command line to your C++ application
Add an interactive command line to your C++ application
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
ZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made Simple
 
I wrote the following change it to having a header, main and cpp fi.pdf
I wrote the following change it to having a header, main and cpp fi.pdfI wrote the following change it to having a header, main and cpp fi.pdf
I wrote the following change it to having a header, main and cpp fi.pdf
 

More from 명신 김

More from 명신 김 (20)

업무를 빼고 가치를 더하는 클라우드 기술
업무를 빼고 가치를 더하는 클라우드 기술업무를 빼고 가치를 더하는 클라우드 기술
업무를 빼고 가치를 더하는 클라우드 기술
 
[2020 Ignite Seoul]Azure에서 사용할 수 있는 컨테이너/오케스트레이션 기술 살펴보기
[2020 Ignite Seoul]Azure에서 사용할 수 있는 컨테이너/오케스트레이션 기술 살펴보기[2020 Ignite Seoul]Azure에서 사용할 수 있는 컨테이너/오케스트레이션 기술 살펴보기
[2020 Ignite Seoul]Azure에서 사용할 수 있는 컨테이너/오케스트레이션 기술 살펴보기
 
Best of Build Seoul 2019 Keynote
Best of Build Seoul 2019 KeynoteBest of Build Seoul 2019 Keynote
Best of Build Seoul 2019 Keynote
 
Passwordless society
Passwordless societyPasswordless society
Passwordless society
 
DevOps and Azure Devops 소개, 동향, 그리고 기대효과
DevOps and Azure Devops 소개, 동향, 그리고 기대효과DevOps and Azure Devops 소개, 동향, 그리고 기대효과
DevOps and Azure Devops 소개, 동향, 그리고 기대효과
 
Serverless design and adoption
Serverless design and adoptionServerless design and adoption
Serverless design and adoption
 
Durable functions
Durable functionsDurable functions
Durable functions
 
Azure functions v2 announcement
Azure functions v2 announcementAzure functions v2 announcement
Azure functions v2 announcement
 
Azure functions
Azure functionsAzure functions
Azure functions
 
Logic apps
Logic appsLogic apps
Logic apps
 
Serverless
ServerlessServerless
Serverless
 
Azure event grid
Azure event gridAzure event grid
Azure event grid
 
Serverless, Azure Functions, Logic Apps
Serverless, Azure Functions, Logic AppsServerless, Azure Functions, Logic Apps
Serverless, Azure Functions, Logic Apps
 
Microservices architecture
Microservices architectureMicroservices architecture
Microservices architecture
 
Visual studio 2015를 활용한 개발 생산성 및 코드 품질 혁신
Visual studio 2015를 활용한 개발 생산성 및 코드 품질 혁신Visual studio 2015를 활용한 개발 생산성 및 코드 품질 혁신
Visual studio 2015를 활용한 개발 생산성 및 코드 품질 혁신
 
Connect(); 2016 한시간 총정리
Connect(); 2016 한시간 총정리Connect(); 2016 한시간 총정리
Connect(); 2016 한시간 총정리
 
크로스 플랫폼을 품은 오픈 소스 프레임워크 .NET Core
크로스 플랫폼을 품은 오픈 소스 프레임워크 .NET Core크로스 플랫폼을 품은 오픈 소스 프레임워크 .NET Core
크로스 플랫폼을 품은 오픈 소스 프레임워크 .NET Core
 
Coded UI test를 이용한 테스트 자동화
Coded UI test를 이용한 테스트 자동화Coded UI test를 이용한 테스트 자동화
Coded UI test를 이용한 테스트 자동화
 
VS2015 C++ new features
VS2015 C++ new featuresVS2015 C++ new features
VS2015 C++ new features
 
Welcome to the microsoft madness
Welcome to the microsoft madnessWelcome to the microsoft madness
Welcome to the microsoft madness
 

Recently uploaded

Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 

Recently uploaded (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 

C++ Lambda and concurrency

  • 1. Lambda Expression & Concurrency API 김명신 부장 Principal Technical Evangelist
  • 3.
  • 4.
  • 6. [lambda-capture] { body } [lambda-capture] (params) { body } [lambda-capture] (params) -> ret { body } [lambda-capture] (params) mutable exception attribute -> ret { body }
  • 7. [lambda-capture] (params) mutable exception attribute -> ret { body } int x = 10, y = 20; [] {}; // capture 하지 않음 [x](int arg) { return x;}; // value(Copy) capture x [=] { return x;}; // value(Copy) capture all [&] { return y;}; // reference capture all [&, x] { return y;}; // reference capture all except x [=, &y] { return x;}; // value(Copy) capture all except y [this] { return this->something;}; // this capture [=, x] {}; // error [&, &x] {}; // error [=, this] {}; // error [x, x] {}; // error Capture default =, &를 하였더라도 body에서 사용하지 않았다면 capture는 일어나지 않음
  • 8. [lambda-capture] (params) mutable exception attribute -> ret { body } [](int &factor, int total) { if (factor == 0) return total; return factor; }; [](float &factor, double total) -> double { if (factor == 0) return total; return factor; };
  • 9. [lambda-capture] (params) mutable exception attribute -> ret { body } [x]() mutable { return ++x; }; [x]() throw() { if (x == 0) throw std::bad_exception(); // warning };
  • 10.
  • 11. cout << typeid([] {}).name() << endl; class <lambda_04197a50f746795ff56aab1f0f0bfa52>
  • 12.
  • 13. int x = 10, y = 20; [x] { return ++x; }; [x, &] { return x + y; }; [=, x] { return x; }; []() noexcept { throw bad_exception(); }; [x]() mutable { return ++x; }; [&, x] { return x + y; }; [=] { return ++x; }; [] { throw bad_exception(); };
  • 14. int x = 1; cout << x << endl; [x]() mutable { ++x; }(); cout << x << endl; [&x]() { ++x; }(); cout << x << endl; 1 1 2
  • 15. 1 2 2 void fa(int x, function<void(void)> f) { ++x; f(); } void fb(int x, function<void(int)> f) { ++x; f(x); } void fc(int &x, function<void(void)> f) { ++x; f(); } int x = 1; fa(x, [x] { cout << x << endl; }); fb(x, [](int x) { cout << x << endl; }); fc(x, [&x] { cout << x << endl; });
  • 16. struct Less { bool operator()(const int &left, const int &right) const { return left < right; } }; sort(begin(v), end(v), Less()); sort(begin(v), end(v), [](int x, int y) { return x < y; });
  • 17. template<typename T> class Less_than { const T val; public: Less_than(const T& v) : val(v) {}; bool operator()(const T& x) const { return x < val; }; }; int num = 5; Less_than<int> less5{ num }; auto diff = count_if(begin(v), end(v), less5); auto diff = count_if(begin(v), end(v), [num](int value) { return value < num; });
  • 18. // return lambda function auto addtwointegers = [](int x) -> function<int(int)> { return [=](int y) { return x + y; }; }; // lambda function as parameter auto higherorder = [](const function<int(int)>& f, int z) { return f(z) * 2; }; auto answer = higherorder(addtwointegers(7), 8);
  • 19. WNDCLASSEX wcex; wcex.lpfnWndProc= [](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT { switch (message) { case WM_COMMAND: EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL { char szText[256]; GetWindowTextA(hwnd, szText, 256); cout << szText << endl; return TRUE; }, 0);
  • 20. HANDLE hT = CreateThread(NULL, 0, [](LPVOID lpThreadParameter) -> DWORD { for (int i = 0; i < 1000; i++) { this_thread::sleep_for(milliseconds{ 10 }); cout << i << endl; } return 0; }, NULL, 0, NULL);
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36. void f2(const int arg) { cout << "f2(" << arg << ")" << endl; } void f3(const int arg, int *pResult) { cout << "f3(" << arg << ")" << endl; *pResult = arg; } int _tmain(int argc, _TCHAR* argv []) { thread t1([] { cout << "f1()" << endl; }); // lambda expression thread t2(f2, 10); // passing argument int result; thread t3(f3, 10, &result); // how to get the result t1.join();t2.join(); t3.join(); // barrier cout << "Result = " << result << endl; }
  • 37. void f2(const int arg) { cout << "f2(" << arg << ")" << endl; } void f3(const int arg, int *pResult) { cout << "f3(" << arg << ")" << endl; *pResult = arg; } int f4(const int arg) { cout << "f4(" << arg << ")" << endl; return arg; } int _tmain(int argc, _TCHAR* argv []) { auto t1 = async([] { cout << "f1()" << endl; }); // lambda expression auto t2 = async(f2, 10); // passing argument int result; auto t3 = async(f3, 10, &result); // how to get the result t1.get(); t2.get(); t3.get(); auto t4 = async(f4, 10); // return value result = t4.get(); cout << "Result = " << result << endl; }
  • 38.
  • 40. int sum(int n) { return n == 1 ? 1 : n + sum(n - 1); } .... using value_type = int; promise<value_type> pr; future<value_type> fu = pr.get_future(); int num = 10; pr.set_value(sum(num)); //pr.set_exception(make_exception_ptr(exception("error"))); try { value_type result = fu.get(); cout << result; } catch (exception &ex) { cout << ex.what() << endl; }
  • 41. using value_type = int; promise<value_type> pr; future<value_type> fu = pr.get_future(); int num = 10; thread t{ [&,num] { pr.set_value(sum(num)); //pr.set_exception(make_exception_ptr(exception("error"))); }}; try { value_type result = fu.get(); cout << result; } catch (exception &ex) { cout << ex.what() << endl; } t.join();
  • 42.
  • 43. get() set_value(x) set_exception(x) return x; throw x; try { pr.set_value(tsk(args)); } catch (...) {pr.set_exception(current_exception()); }
  • 44. using value_type = int; packaged_task<value_type(int)> pt{ sum }; future<value_type> fu = pt.get_future(); int num = 10; pt(num); try { value_type result = fu.get(); cout << result; } catch (exception &ex) { cout << ex.what() << endl; }
  • 45. using value_type = int; packaged_task<value_type(int)> pt{ sum }; future<value_type> fu = pt.get_future(); int num = 10; thread t{ move(pt), 10 }; try { value_type result = fu.get(); cout << result; } catch (exception &ex) { cout << ex.what() << endl; } t.join();
  • 46. void producer() { int x = 1; while (x) { packaged_task<int()> pt{ bind(sum, x++) }; { unique_lock<mutex> ul(mtx); q.push_back(move(pt)); } cond.notify_one(); this_thread::sleep_for(milliseconds{ 100 }); } } void consumer() { while (true) { packaged_task<int(void)> pt; { unique_lock<mutex> ul(mtx); cond.wait(ul, [] {return !q.empty(); }); pt = move(q.front()); } pt(); cout << pt.get_future().get() << endl; q.pop_front(); } } int sum(int n) { return n == 1 ? 1 : n + sum(n - 1); } deque<packaged_task<int()> > q; mutex mtx; condition_variable cond;
  • 47. using value_type = int; future<value_type> fu = async(sum, 10); try { value_type result = fu.get(); cout << result; } catch (exception &ex) { cout << ex.what() << endl; }