thread — std::thread

thread — std::thread

std::thread 클래스는 단일 실행 스레드 하나를 나타내요. C++11에서 도입됐어요. <thread> 헤더에 있어요.

스레드는 여러 함수를 동시에 실행할 수 있게 해줘요.

출처: cppreference

본문

// <thread> 헤더, C++11
class thread;

스레드는 연관 thread 객체의 생성과 동시에 실행을 시작해요 (보류 중인 OS 스케줄링 지연 후).

사용 예

#include <thread>
#include <iostream>

void worker(int id) {
    std::cout << "thread " << id << '\n';
}

int main() {
    std::thread t1(worker, 1);   // 호출 가능한 것 + 인자
    std::thread t2([] { std::cout << "lambda\n"; });

    t1.join();   // 완료 대기 (필수!)
    t2.join();
}

주요 멤버

멤버 설명
join() 스레드 종료까지 블로킹 후 대기
detach() 스레드를 분리 (수명 독립)
joinable() join/detach 가능 여부
get_id() 스레드 id
hardware_concurrency() (정적) 하드웨어 스레드 수

join vs detach

std::thread t(worker);
t.join();    // 완료까지 기다림 (권장)

// detach: 스레드 수명을 독립시킴 (주의 — 객체 수명과 무관)
std::thread t2([]{ /* ... */ });
t2.detach();

파괴 시 규칙

std::thread는 파괴 시점에 joinable()이면 **std::terminate**를 호출해요 (join이나 detach를 하지 않으면). 그래서 항상 join() 또는 detach()를 호출해야 해요.

#include <thread>
#include <vector>

std::vector<std::thread> threads;
for (int i = 0; i < 4; ++i)
    threads.emplace_back(worker, i);
for (auto& t : threads) t.join();   // 모두 대기

함수·메서드·인자

std::thread t(&MyClass::method, &obj, args...);   // 멤버 함수
std::thread t(fn, std::ref(x));                   // 참조 전달은 std::ref

std::thread는 가장 기본적인 스레드 생성 도구예요. 다만 파괴 시 terminate가 될 수 있어 C++20의 std::jthread(자동 join)가 더 권장돼요.

더 알아보기 (Learn more)

cppreference