thread_swap2

thread_swap2 (std::thread 전용 swap 함수)

이 페이지는 std::thread를 위한 std::swap 알고리즘 오버로드에 대해 설명해요. 이 함수는 두 스레드 객체의 상태를 서로 교환하는 데 사용돼요. C++11부터 사용할 수 있어요.

출처: cppreference

본문

개요

std::thread를 위해 std::swap 알고리즘을 오버로드해요. lhsrhs의 상태를 서로 교환해요. 실제로는 lhs.swap(rhs)를 호출해요.

매개변수

lhs, rhs - 상태를 교환할 스레드들이에요.

반환값

(없음)

예제

#include <chrono>
#include <iostream>
#include <thread>

void foo()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

void bar()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{
    using std::swap;

    std::thread t1(foo);
    std::thread t2(bar);

    std::cout << "thread 1 id: " << t1.get_id() << '\n'
              << "thread 2 id: " << t2.get_id() << '\n';

    swap(t1, t2);

    std::cout << "after std::swap(t1, t2):" << '\n'
              << "thread 1 id: " << t1.get_id() << '\n'
              << "thread 2 id: " << t2.get_id() << '\n';

    t1.swap(t2);

    std::cout << "after t1.swap(t2):" << '\n'
              << "thread 1 id: " << t1.get_id() << '\n'
              << "thread 2 id: " << t2.get_id() << '\n';

    t1.join();
    t2.join();
}

가능한 출력 결과는 다음과 같아요.

thread 1 id: 1892
thread 2 id: 2584
after std::swap(t1, t2):
thread 1 id: 2584
thread 2 id: 1892
after t1.swap(t2):
thread 1 id: 1892
thread 2 id: 2584

같이 보기

swap 두 thread 객체를 교환해요 (public 멤버 함수) [편집]

더 알아보기 (Learn more)

cppreference