Skip to main content

One post tagged with "singleton"

View All Tags

· One min read
Hreniuc Cristian-Alexandru

I had to create a conditional singleton object and I tried something but it didn't look so good. And while doing this I've noticed that I colleague did something like this:

static const auto executor = []() -> smt_type
{
return smt;
}();

Which creates a lamba and calls it inplace.

And I liked it so much that I ended up asking him about it and he showed me this post from Herb Sutter. So I ended up doing something like this:

static const auto executor = []() -> std::shared_ptr<Aws::Utils::Threading::PooledThreadExecutor>
{
if(!isActive())
{
return nullptr;
}
size_t workers{0};
auto const downloadWorkersStr = getenv("env_var");
if(downloadWorkersStr)
{
// Env variable overrides the config
workers = stoi(downloadWorkersStr);
}
else
{
workers = getWorkerThreadsFromConfig();
}

if(workers == 0)
{
workers = boost::thread::hardware_concurrency();
}
return Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>(
"", workers);
}();
return executor;

This is called only once and it's also thread safe.