Post List

C++ Thread Basic


std::thread

windows의 경우 beginthreadex , OS독립적으로는 pthread 등을 사용했다. 이 방식들은 arg를 1개만 줄 수 있었다. 물론 struct나 pointer로 넘기면 여러개가 가능하지만 요즘 누가 그렇게 쓰나. modern c++로 진입하면서 standard로 쓰레드를 편하게 사용할 수 있게 되었다.

include

#include <thread>
간단하다 thread 를 include하면 된다.

Create thread

스레드를 만들 때 함수를 넣어주면 된다. 람다도 되고, 함수 객체로도 된다.
// target function
int add(int a, int b) { return a + b; }
// target class
class Target {
public:
    void process() {}
}

// function pointer
std::thread t1(add, 1, 2);
// lambda
std::thread t1([a, b] { return a + b; });
// class function
Target target;
std::thread t1(&Target::process, &target);

Run thread

보편적으로 두가지 방법이 있다. 메인스레드가 기다리게 만드는 join 과 돌려놓고 딴짓하는 detach 이다.
// wait the thread to finish
t1.join();
// async
t1.detach();

0 개의 댓글:

댓글 쓰기