modern c++ concurrency api

24
Effective Modern C++ Study Concurrency API (Preview) 윤석준 / C++ Korea

Upload: seok-joon-yun

Post on 14-Jul-2015

498 views

Category:

Software


7 download

TRANSCRIPT

Effective Modern C++ Study Concurrency API (Preview)

윤석준 / C++ Korea

Overview

vector<vector<int>>

user-defined literals thread_local

=default, =delete atomic<T> auto f() -> int

array<T, N>

decltype vector<LocalType>

noexcept regex

initializer lists

constexpr

extern template

unordered_map<int, string> raw string literals

nullptr auto i = v.begin();

async

lambdas []{ foo(); }

template aliases

unique_ptr<T> shared_ptr<T> weak_ptr<T>

thread, mutex

for (x : coll)

override, final

variadic templates template <typename T…>

function<>

promise<T>/future<T>

tuple<int, float, string> strongly-typed enums

enum class E {…};

static_assert(x)

rvalue references (move semantics)

delegating constructors

packaged_task<T>

Overview

vector<vector<int>>

user-defined literals thread_local

=default, =delete atomic<T> auto f() -> int

array<T, N>

decltype vector<LocalType>

noexcept regex

initializer lists

constexpr

extern template

unordered_map<int, string> raw string literals

nullptr auto i = v.begin();

async

lambdas []{ foo(); }

template aliases

unique_ptr<T> shared_ptr<T> weak_ptr<T>

thread, mutex

for (x : coll)

override, final

variadic templates template <typename T…>

function<>

promise<T>/future<T>

tuple<int, float, string> strongly-typed enums

enum class E {…};

static_assert(x)

rvalue references (move semantics)

delegating constructors

packaged_task<T>

① Core 내부 병렬 프로그래밍

② Thread 병렬 프로그래밍

③ Process 병렬 프로그래밍

④ GPGPU를 이용한 병렬 프로그래밍

SIMD

OpenMP, PPL, pthreads

MPI

CUDA, OpenCV

Concurrency API in Modern C++

- include

- using, namespace

지금부터 예제에서 생략할 내용들

#include <iostream> #include <thread> #include <future> #include <chrono> #include <utility> using std::cout; using std::endl; using std::vector; using std::promise; using std::future; using std::thread; using std::ref; using std::move; using std::this_thread::get_id; using std::this_thread::sleep_for; using namespace std::chrono;

#include <thread>

join() : 종료까지 대기 : Blocking

detach() : thead object 분리

swap() : thread object 끼리 교환

get_id() : thread id 확인

sleep_for(), sleep_until(), yield()

thread_local : 각 thread별로 따로 생성

http://msdn.microsoft.com/ko-kr/library/hh920601.aspx

System Level의 Thread 생성

thread t1([] // 생성과 동시에 실행 { for (int i = 0; i < 5; i++) { cout << "Thread1[" << get_id() << "] : " << i << endl; sleep_for(milliseconds(500)); } }); thread t2; // 생성 후 특정시점에 실행 t2 = thread([] { seconds tick(1); auto StartTime = system_clock::now(); for (int i = 0; i < 5; i++) { cout << "Thread2[" << get_id() << "] : " << i << endl; sleep_until(StartTime + tick * i); } });

http://devluna.blogspot.kr/2014/12/thread.html

thread t3 = std::thread([](int nParam) // Parameter 추가 { for (int i = 0; i < 5; i++) cout << "Thread3[" << get_id() << "] : " << nParam << endl; }, 4);

#include <mutex>

lock(), unlock(), try_lock() : mutex 동작제어

lock_guard : mutex lock의 RAII pattern

recursive_mutex : 중첩 lock 허용

timed_mutex : timed_lock_for(), timed_lock_until()

call_once() : 한번만 실행

http://msdn.microsoft.com/ko-kr/library/hh921447.aspx

Lock을 이용하여 Task간 동기화 구현

#include <condition_variable>

wait(), wait_for(), wait_until() : notify 대기

notify_one(), notify_all() : wait 깨우기

http://msdn.microsoft.com/ko-kr/library/hh874752.aspx

mutex를 활용하여 task 간의 동기화

#include <atomic>

+, -, AND, OR, XOR 등 …

atomic_exchange(), atomic_compare_exchange()

Compiler 에 따라 Lock으로 동작 할 수도 있다.

http://msdn.microsoft.com/ko-kr/library/hh874894.aspx

Lock-free로 변수 하나에 대한 동기화

#include <future>

auto a = async(launch policy, Fn&& fn, ArgTypes&& … args);

a.get();

std::launch::async : 가능할때 먼저 실행

std::launch::deferred : get() 호출할 때 실행

http://msdn.microsoft.com/ko-kr/library/hh920568.aspx

비동기로 수행가능한 task 생성 후 이를 수행할 thread를 system에게 위임

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; } void main() { future<void> t1 = async([] { cout << "f1()" << endl; }); // lambda expression auto t2 = async(f2, 10); // passing argument int result = -1; auto t3 = async(f3, 10, &result); // how to get the result cout << "[T3 : before get()] Result = " << result << endl; t1.get(); t2.get(); t3.get(); cout << "[T3 : after get()] Result = " << result << endl; auto t4 = async(f4, 10); // return value result = t4.get(); cout << "[T4 : ager get()] Result = " << result << endl; }

http://devluna.blogspot.kr/2014/12/async.html

void GetTestVector(promise<vector<int>>& p, int p_nStart, int p_nNum) { cout << "GetTestVector : " << get_id() << endl; vector<int> v; for (int i = 0; i < p_nNum; ++i) v.push_back(i + p_nStart); p.set_value(move(v)); cout << "End of GetTestVector" << endl; } void PrintTestVector(future<vector<int>>& f, thread& t) { cout << "PrintTestVector : " << get_id() << endl; auto result = f.get(); for (auto item : result) cout << "Get Values : " << item << endl; cout << "End of PrintTestVector" << endl; }

http://devluna.blogspot.kr/2015/01/thread-async-promisefuture.html

void main() { promise<vector<int>> p; future<vector<int>> f = p.get_future(); thread t; thread t2(&PrintTestVector, ref(f), ref(t)); sleep_for(milliseconds(500)); t = thread(&GetTestVector, ref(p), 11, 7); t.join(); t2.join(); }

std::vector<int> GetTestVector(int p_nStart, int p_nNum) { vector<int> V; for (int i = 0; i < p_nNum; ++i) { V.push_back(i + p_nStart); } return V; } void main() { packaged_task<vector<int>(int, int)> task(&GetTestVector); future<vector<int>> f = task.get_future(); thread t(move(task), 21, 7); t.detach(); auto result = f.get(); for (auto i : result) { cout << "Get Values : " << i << endl; } }

http://devluna.blogspot.kr/2015/01/thread-packagedtask.html

감사합니다.

https://www.facebook.com/seokjoon.yun.9

http://devluna.blogspot.kr/