11. - 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;
12. #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 생성
13. 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);
15. #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 간의 동기화
16. #include <atomic>
+, -, AND, OR, XOR 등 …
atomic_exchange(), atomic_compare_exchange()
Compiler 에 따라 Lock으로 동작 할 수도 있다.
http://msdn.microsoft.com/ko-kr/library/hh874894.aspx
Lock-free로 변수 하나에 대한 동기화
17. #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에게 위임
18. 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