본문 바로가기

[C++11] thread

thread를 표준 라이브러리로 지원한다.

 

1. 일반 함수를 스레드 함수로 사용

#include <iostream>
#include <thread>

// 스레드에서 실행될 함수
void threadFunction(int id) {
    std::cout << "Hello from thread " << id << std::endl;
}

int main() {
    std::cout << "Main thread starts" << std::endl;

    // 스레드 생성 및 시작
    std::thread t1(threadFunction, 1); // threadFunction을 id 1로 실행
    std::thread t2(threadFunction, 2); // threadFunction을 id 2로 실행

    // 메인 스레드에서 다른 작업 수행
    std::cout << "Hello from main thread" << std::endl;

    // 스레드가 끝날 때까지 기다림
    t1.join();
    t2.join();

    std::cout << "Main thread ends" << std::endl;

    return 0;
}

 

 

2. 클래스 멤버 함수를 스레드 함수로 사용

#include <iostream>
#include <thread>

class MyClass {
public:
    void threadFunction(int id) {
        std::cout << "Hello from thread " << id << std::endl;
    }
};

int main() {
    std::cout << "Main thread starts" << std::endl;

    MyClass obj;

    // 멤버 함수 포인터를 사용하여 스레드 생성
    std::thread t1(&MyClass::threadFunction, &obj, 1);
    std::thread t2(&MyClass::threadFunction, &obj, 2);

    // 메인 스레드에서 다른 작업 수행
    std::cout << "Hello from main thread" << std::endl;

    // 스레드가 끝날 때까지 기다림
    t1.join();
    t2.join();

    std::cout << "Main thread ends" << std::endl;

    return 0;
}

 

3. 클래스 멤버 함수 내에서, 자기 자신을 객체(this)로 전달하여 스레드 생성

#include <iostream>
#include <thread>

class MyClass {
public:
    void threadFunction(int id) {
        std::cout << "Hello from thread " << id << std::endl;
    }

    void runThreads() {
        // 멤버 함수를 스레드로 실행
        std::thread t1(&MyClass::threadFunction, this, 1);
        std::thread t2(&MyClass::threadFunction, this, 2);

        // 메인 스레드에서 다른 작업 수행
        std::cout << "Hello from main thread" << std::endl;

        // 스레드가 끝날 때까지 기다림
        t1.join();
        t2.join();
    }
};

int main() {
    std::cout << "Main thread starts" << std::endl;

    MyClass obj;
    obj.runThreads();

    std::cout << "Main thread ends" << std::endl;

    return 0;
}

 

'C&C++' 카테고리의 다른 글

[C++] 소수점 출력  (0) 2024.07.28
[C++] std::string  (0) 2024.07.07
[C++17] filesystem  (0) 2024.06.29
[C++11] constexpr  (0) 2024.06.23
[C++11] nullptr  (0) 2024.06.23