Search code examples
c++multithreadingconcurrencyc++20semaphore

How to initialize the LeastMaxValue template param in counting_semaphore?


I have a use case where I need to use counting_semaphore as a data member in a class. If it were a global variable, I could've omitted the template argument, and it would've been default initialized. But as mentioned here, in case of a member variable, the template argument needs to be specified, and in our case it has to be a compile-time constant.

So, I'm not sure what to initalize the value of LeastMaxValue to? Are there any heuristics for it that you use, or is there a way I can still use the implementation defined default value for this?


Solution

  • Ideally, you would look at how the data member will be used and determine an upper bound on what the semaphore needs to count. This upper bound is an appropriate LeastMaxValue.

    It is not always possible to find such a bound, though. If you have no way of bounding the maximum the data member needs to handle, you could use the largest possible value, std::numeric_limits<std::ptrdiff_t>::max().