ThreadSchedule 3.0.0
Modern C++ thread management library
Loading...
Searching...
No Matches
worker_count.hpp
Go to the documentation of this file.
1#pragma once
2
8#include "result.hpp"
9
10#include <algorithm>
11#include <cstddef>
12#include <stdexcept>
13#include <thread>
14
15namespace threadschedule
16{
17
25{
26public:
28 worker_count() noexcept = default;
34 explicit worker_count(std::size_t value) : value_(checked(value)) {}
35
40 [[nodiscard]] static constexpr auto
41 automatic() noexcept -> worker_count
42 {
43 return worker_count(automatic_tag{});
44 }
45
51 [[nodiscard]] static auto
52 create(std::size_t value) noexcept -> result<worker_count>
53 {
54 if (value == 0)
55 return unexpected(std::make_error_code(std::errc::invalid_argument));
56 return worker_count(unchecked_tag{}, value);
57 }
58
60 [[nodiscard]] constexpr auto
61 is_automatic() const noexcept -> bool
62 {
63 return value_ == 0;
64 }
65
70 [[nodiscard]] auto
71 resolve() const noexcept -> std::size_t
72 {
73 if (!is_automatic())
74 return value_;
75 return std::max<std::size_t>(1, std::thread::hardware_concurrency());
76 }
77
78private:
79 struct automatic_tag
80 {
81 };
82 struct unchecked_tag
83 {
84 };
85
86 constexpr explicit worker_count(automatic_tag) noexcept {}
87 constexpr worker_count(unchecked_tag, std::size_t value) noexcept : value_(value) {}
88
89 [[nodiscard]] static auto
90 checked(std::size_t value) -> std::size_t
91 {
92 if (value == 0)
93 throw std::invalid_argument("worker_count must be positive");
94 return value;
95 }
96
97 std::size_t value_{ 0 };
98};
99
100} // namespace threadschedule
Value type for pool worker count.
auto resolve() const noexcept -> std::size_t
Resolve the effective worker count.
worker_count() noexcept=default
Construct automatic worker count.
static constexpr auto automatic() noexcept -> worker_count
Create automatic worker count.
constexpr auto is_automatic() const noexcept -> bool
Return whether this instance uses automatic resolution.
static auto create(std::size_t value) noexcept -> result< worker_count >
Create explicit worker count without exceptions.
Error-returning result type used by the portable ThreadSchedule API.