Namespaces
Variants

swap (std::jthread)

From cppreference.net

Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
friend void swap ( jthread & lhs, jthread & rhs ) noexcept ;
(C++20 이후)

std::swap 알고리즘을 std::jthread 에 대해 오버로드합니다. lhs 의 상태와 rhs 의 상태를 교환합니다. 효과적으로 lhs. swap ( rhs ) 를 호출합니다. 이 함수는 일반적인 비한정(unqualified) 또는 한정된(qualified) 조회 로는 보이지 않으며, std::jthread가 인자의 연관 클래스일 때만 인자 종속 조회(argument-dependent lookup) 를 통해 찾을 수 있습니다.

목차

매개변수

lhs, rhs - 상태를 교환할 jthread 객체들

반환값

(없음)

예제

#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::jthread t1(foo);
    std::jthread 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';
}

가능한 출력:

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

참고 항목

두 jthread 객체를 교환
(public member function)