ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • C++20 코루틴 기능을 활용한 비동기 프로그래밍 예제
    프로그래밍/C/C++ 2023. 2. 23. 10:03

    ✨C++로도 비동기 프로그래밍을 구현할 수 있어요!✨

    C++11부터는 C++ 표준 라이브러리에 스레드, 뮤텍스, 조건 변수와 같은 다중 스레드 지원 기능이 추가되어, 비동기 프로그래밍을 구현할 수 있게 되었어요! 또한 C++11에서는 표준 라이브러리에 비동기 처리를 위한 기능들을 추가했습니다.

    C++11에서 추가된 비동기 처리 기능은 std::async, std::future, std::promise, std::packaged_task 등이 있어요. std::async를 사용하면 비동기 함수 호출을 간단하게 작성할 수 있고, std::future를 사용하여 비동기 함수 호출 결과를 받을 수 있어요. 또한, std::promise와 std::packaged_task를 사용하여 비동기 함수 호출 결과를 만들고 다른 스레드에서 가져올 수 있어요.

    C++11 이후로는 C++14, C++17에서도 비동기 처리 기능이 추가되었으며, 더욱 발전된 비동기 프로그래밍 기술을 사용할 수 있게 되었어요. 또한, C++20에서는 코루틴(Coroutine)이 추가되어 비동기 프로그래밍을 더욱 쉽고 직관적으로 작성할 수 있게 되었어요!

    🌟C++20에서 새로 추가된 코루틴(Coroutine)은 비동기 프로그래밍을 더욱 쉽게 구현할 수 있게 도와줘요!🌟

    아래는 C++20에서 코루틴을 사용하여 간단한 예제를 구현한 것이에요.

    #include <iostream>
    #include <coroutine>
    #include <chrono>
    
    using namespace std::chrono_literals;
    
    class Task {
    public:
        struct promise_type {
            Task get_return_object() { return Task{ handle_type::from_promise(*this) }; }
            std::suspend_always initial_suspend() { return {}; }
            std::suspend_always final_suspend() noexcept { return {}; }
            void return_void() {}
            void unhandled_exception() {}
        };
    
        using handle_type = std::coroutine_handle<promise_type>;
    
        explicit Task(handle_type handle) : handle_(handle) {}
        Task(Task&& t) noexcept : handle_(t.handle_) { t.handle_ = nullptr; }
        Task& operator=(Task&& other) noexcept {
            if (handle_) handle_.destroy();
            handle_ = other.handle_;
            other.handle_ = nullptr;
            return *this;
        }
        ~Task() { if (handle_) handle_.destroy(); }
    
        void resume() { handle_.resume(); }
        bool done() const { return handle_.done(); }
    
    private:
        handle_type handle_;
    };
    
    Task count(int from, int to) {
        for (int i = from; i <= to; ++i) {
            std::cout << i << '\\\\n';
            co_await std::chrono::seconds(1);
        }
    }
    
    int main() {
        Task t = count(1, 10);
        while (!t.done()) {
            t.resume();
        }
        return 0;
    }
    
    

    💻 이 코드는 1부터 10까지의 숫자를 1초 간격으로 출력하는 함수를 코루틴으로 구현한 예제입니다. 이 코드에서 Task 클래스는 코루틴 핸들을 감싸는 래퍼 클래스로, count 함수는 코루틴을 정의합니다. main 함수에서는 Task 객체를 생성하고, done 함수를 호출하여 작업이 완료될 때까지 resume 함수를 반복적으로 호출합니다.

    🚀 C++20에서 코루틴을 사용하면 비동기 처리를 간단하게 구현할 수 있어요. 이 예제에서는 std::chrono::seconds 함수를 사용하여 일정 시간 동안 코루틴을 일시 중단합니다. 이 외에도 C++20에서는 co_await 키워드를 사용하여 다른 코루틴이나 비동기 작업을 기다리는 등의 기능을 제공합니다.

    댓글

Designed by Tistory.