/*
Waiting for a thread to complete
*/
#include <thread>
struct Callable
{
const int& _i;
Callable(const int& i) : _i(i)
{}
void operator()()
{
for (unsigned int j = 0; j < 1000000; j++)
{
do_something();
}
}
void do_something()
{
// Do something
}
};
struct thread_guard
{
std::thread& _t;
explicit thread_guard(std::thread& t) : _t(t)
{}
~thread_guard()
{
// Join can be called only once for a given thread
if (_t.joinable())
{
_t.join();
}
}
// Prevent creating copied of this object since copying the reference to the thread might be dangerous
thread_guard(const thread_guard&) = delete;
thread_guard& operator=(const thread_guard&) = delete;
};
void CreateThreads()
{
int some_local_state;
// Object with a reference to the local variable
Callable c(some_local_state);
std::thread t(c);
// Thread guard will make sure that the function doesn't return without finishing the thread
thread_guard g(t);
}
int main()
{
CreateThreads();
}