#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <latch>
#include <format>
using namespace std::chrono_literals;
void ThreadFunction(int threadNumber, std::latch& latch) {
for (int i{ 0 }; i < 5; i++) {
std::cout << std::format("Thread {} is running, Iteration : {}\n", threadNumber, i);
std::this_thread::sleep_for(1s);
}
latch.count_down();
}
int main()
{
constexpr int NUM_THREADS = 3;
std::latch completion_latch{ NUM_THREADS };
std::vector <std::jthread> threads;
for (int i{ 0 }; i < NUM_THREADS; i++) {
threads.emplace_back([i, &completion_latch](std::stop_token stopToken) {
ThreadFunction(i + 1, completion_latch);
});
}
completion_latch.wait();
std::cout << "All Threads have completed.\n";
}
- std::jthread를 사용합니다. 이는 C++20에서 도입된 새로운 스레드 클래스로, 자동으로 join을 수행하며 취소 요청을 지원합니다.
- std::latch를 사용하여 모든 스레드의 완료를 동기화합니다. 이는 C++20에서 도입된 새로운 동기화 프리미티브입니다.
- std::format을 사용하여 문자열 포매팅을 수행합니다. 이는 C++20의 새로운 기능으로, 타입 안전한 문자열 포매팅을 제공합니다.
- std::chrono_literals를 사용하여 시간 단위를 더 읽기 쉽게 표현합니다. (1s)
- 람다 함수를 사용하여 각 스레드의 작업을 정의합니다.
- std::vector를 사용하여 스레드 객체들을 관리합니다.
'C++ > 기초' 카테고리의 다른 글
c++20 간결하게 코드쓰기(1) (0) | 2024.10.19 |
---|