Language/C++11 [C++] std::jthread std::thread 사용시 - 반드시 join 또는 detach 해야한다. std::jthread - C++20 에서 추가된 새로운 스레드 클래스 - - 소멸자에서 join을 해준다.#include #inlcude #include using namespace std::literals;void foo(int a, double b) { std::cout jthread에서 stop token 예제#include #include #include using namespace std::literals;void foo() { for (int i = 0 ; i 2025. 1. 6. [C++] std::async std::async- 주어진 함수를 비동기 (asynchronous)로 수행하는 함수 템플릿- 기존에 작성된 함수를 간단하게 스레드로 수행할 수 있다.- 일반적인 구현은 스레드 풀 사용- std::future 반환 1. std::async 기본 예제#include #include #include #include using namespace std::literals;int add(int a, int b) { std::this_thread::sleep_for(2s); return a+b;}int main() { std::future ft = std::async(add, 10, 20); std::cout - 위 예제에서 ft.get()을 호출하지 않아도 future의 소멸자에서 get()을 호출하여.. 2024. 12. 20. [C++] std::packaged_task 멀티쓰레드를 고려하지 않은 일반 함수에 대해서 값을 꺼내오고 싶을때 사용std::packaged_task 예제#include #include #include int add(int a, int b){ std::cout task(add); std::future ft = task.get_future(); std::thread t(std::move(task), 10, 20); int ret = ft.get(); std::cout 2024. 12. 18. [C++] std::promise, std::future std::promise - 스레드 사이에서 "값 또는 예외를 공유" 할 수 있는 템플릿 - 헤더 - promise 통해서 전달된 데이터는 std::future를 통해서 얻을 수 있다. - set_value()는 한번만 사용할 수 있다. - future()는 한번만 꺼낼 수 있다.std::future 멤버 함수 - get() : 결과를 꺼내기. (한번만 사용 가능) - wait() : 결과값이 준비될 때까지 대기 - wait_for() : 주어진 시간 만큼 대기 - wait_until() : 주어진 시간까지 대기 -> wait_for/wait_until 함수의 반환값 - std::future_status::ready : 결과값이 준비 됨. - std::future_status::ti.. 2024. 12. 4. [C++] std::ref, std::reference_wrapper std::ref() - "call by value"를 사용하는 함수 템플릿에 객체를 참조로 보내고 싶을때 사용 - 헤더, C+11부터 지원 std::reference_wrapper #include template struct reference_wrapper { T* obj; public: reference_wrapper(T& t) : obj(&t) {} operator T&() { return *obj; } }; int main() { int n = 0; reference_wrapper rw = n; int& r = rw; // rw.operator int&() r = 100; std::cout 2023. 9. 1. [C++] std::thread 쓰레드를 생성하는 방법 1. std::thread의 생성자로 쓰레드로 수행할 함수 전달. 2. 헤더 필요 3. 객체의 생성이 곧 thread start이다. 4. join()이나 detach()를 해야한다. - join() : 쓰레드 종료를 대기 - detach() : 쓰레드를 떼어 냄 (생성된 쓰레드가 독립적으로 실행) std::thread usage #include void f1() {}; void f2(int a, double d) {} void f3(int a, int& b, std::string&& s) {b = 100;} int main() { int n = 0; std::string s = "hello"; std::thread t1(&f1); std::thread t2(&f2, 10, 3.4.. 2023. 9. 1. 이전 1 2 다음