Std::thread
Tip
- sleep_for와 sleep_until을 사용하면 스레드를 일시 중지 시킬 수 있다.
- sleep_for는 지정한 시간 동안(예 100밀리세컨드 동안만 정지), sleep_until은 지정 시간이까지(예 16시 10분까지 정지)
std::this_thread::yield();
Example
// thread example
#include <iostream> // std::cout
#include <thread> // std::thread
void foo()
{
// do stuff...
}
void bar(int x)
{
// do stuff...
}
int main()
{
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar,0); // spawn new thread that calls bar(0)
std::cout << "main, foo and bar now execute concurrently...\n";
// synchronize threads:
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
std::cout << "foo and bar completed.\n";
return 0;
}
Calling method of class
#include <thread>
// ...
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
// ...
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
Detach thread
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
void pause_thread(int n)
{
std::this_thread::sleep_for (std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds ended\n";
}
int main()
{
std::cout << "Spawning and detaching 3 threads...\n";
std::thread (pause_thread,1).detach();
std::thread (pause_thread,2).detach();
std::thread (pause_thread,3).detach();
std::cout << "Done spawning threads.\n";
std::cout << "(the main thread will now pause for 5 seconds)\n";
// give the detached threads time to finish (but not guaranteed!):
pause_thread(5);
return 0;
}
Thread group
Boost를 사용한 스레드 그룹은 아래와 같다.
#include "boost/thread.hpp"
class threadFunc
{
int m_a;
public:
threadFunc( int a )
{
m_a = a;
}
void operator()()
{
printf("[%d]일단 들어왔네!!! [%d]\n", boost::this_thread::get_id(), m_a );
Sleep(5000);
printf("[%d] 끝났네 [%d]\n", boost::this_thread::get_id(), m_a );
}
};
int main()
{
boost::thread_group tg;
tg.create_thread( threadFunc(1) ); // 1번 스래드 생성
tg.add_thread(new boost::thread( threadFunc(2) ) ); // 2번 스래드 생성
tg.add_thread(new boost::thread( threadFunc(3) ) ); // 3번 스래드 생성
//모든 스래드가 종료 될때까지 대기
tg.join_all();
return 0;
}
See also
Favorite site
- cplusplus.com: std::thread
- cppreference.com: std::thread
- C++ Thread(쓰레드, 스레드)
- C++에서 Thread를 써보자
- C++11 Thread 1. Creating Threads
- C++11에서 추가된 클래스 - thread
- 병렬 프로그래밍. std::thread - 1. 스레드 생성
- 병렬 프로그래밍. std::thread – thread 오브젝트를 join이나 detach하지 않고 파괴했을 때
- 병렬 프로그래밍. std::thread - 6. sleep_for, sleep_until, yield
- Sleep(0)와 SwitchToThread()
- Cross thread calls in native C++
- [추천] c++11 async, corotuine, io 스터디
- [추천] C++11 - C11 / C++11 / POSIX 스레드 API 비교 2