[c++] C++에서의 스레드 중단 및 종료 처리

C++에서 다중 스레드를 사용하다 보면 종료 조건을 설정하고 스레드를 안전하게 중단해야 할 때가 있습니다. 이러한 상황에서 스레드를 중단하고 종료하는 방법을 살펴보겠습니다.

std::thread로 스레드 생성하기

먼저, std::thread를 사용하여 스레드를 생성합니다. 아래의 예시 코드는 std::thread를 사용하여 간단한 작업을 수행하는 스레드를 생성하는 방법을 보여줍니다.

#include <iostream>
#include <thread>

void threadFunction()
{
    // 스레드에서 실행할 작업
    std::cout << "Thread is running" << std::endl;
}

int main()
{
    // 스레드 생성
    std::thread t(threadFunction);

    // 작업이 모두 끝날 때까지 대기
    t.join();

    return 0;
}

std::thread를 통한 스레드 중단

스레드를 중단하기 위해서는 플래그를 사용하여 스레드가 종료되어야 하는지 여부를 확인해야 합니다. 아래의 예시 코드는 이를 보여줍니다.

#include <iostream>
#include <thread>
#include <atomic>

std::atomic<bool> stop(false);

void threadFunction()
{
    while (!stop)
    {
        // 스레드에서 실행할 작업
        std::cout << "Thread is running" << std::endl;
    }
}

int main()
{
    // 스레드 생성
    std::thread t(threadFunction);

    // 스레드 중단
    stop = true;

    // 스레드 종료 대기
    t.join();

    return 0;
}

std::condition_variable을 활용한 스레드 종료 및 중단

std::condition_variablestd::mutex를 사용하여 스레드 중단과 종료를 제어할 수 있습니다. 아래의 예시 코드는 std::condition_variable을 사용하여 스레드를 중단하고 종료하는 방법을 보여줍니다.

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

bool stop = false;
std::mutex m;
std::condition_variable cv;

void threadFunction()
{
    while (true)
    {
        std::unique_lock<std::mutex> lock(m);
        cv.wait(lock, []{ return stop; });
        if (stop)
        {
            // 스레드 종료
            break;
        }
        // 스레드에서 실행할 작업
        std::cout << "Thread is running" << std::endl;
    }
}

int main()
{
    // 스레드 생성
    std::thread t(threadFunction);

    // 스레드 중단
    stop = true;
    cv.notify_one();

    // 스레드 종료 대기
    t.join();

    return 0;
}

위의 예시 코드를 보면, std::condition_variable을 사용하여 스레드가 중단되어야 하는지를 신호하는 방식으로 스레드를 조절하는 것을 확인할 수 있습니다.

결론

C++에서 스레드를 안전하게 중단하고 종료하는 방법을 살펴보았습니다. std::thread의 중단 플래그 및 std::condition_variable를 사용하여 스레드를 제어할 수 있는 방법을 숙지하면 다중 스레드를 안전하게 다루는 데 도움이 될 것입니다.

참고문헌: