When we comile and run the below code it does not invoke the thread. As per concurrency chapter 2 of the C++ Concurrency in Action by Anthony Williams it should work [ page 50 ] Listing example 2.6
The line
ScopedThread t(std::thread(func(some_local_state)));
or
ScopedThread t(std::thread((my_func)));
does not seem to invoke the thread. Why is it treating the thread variable as temporary and avoiding invoking the execution.
#include<iostream>
#include<thread>
using namespace std;
class ScopedThread
{
private:
std::thread t;
public:
explicit ScopedThread(std::thread t_) : t(std::move(t_))
{
if(!t.joinable())
{
cout << "Not throwable" << endl;
throw std::logic_error("No Thread Error!");
}
}
~ScopedThread()
{
t.join();
}
ScopedThread(const ScopedThread& ) = delete;
ScopedThread operator=(const ScopedThread& ) = delete;
};
void do_something(const int& ref)
{
int temp=ref;
cout << "inside do_something at id = " << ref << endl;
}
struct func
{
int& i;
func(int& i_) : i(i_) { }
void operator ()()
{
for(unsigned j=0; j<100; ++j)
{
do_something(i);
}
}
};
void some_func()
{
int some_local_state = 42;
func my_func(some_local_state);
// Both below lines [ uncomment each at one time ]
// ScopedThread t(std::thread(func(some_local_state)));
// ScopedThread t(std::thread((my_func)));
}
int main(int argc, char* argv[])
{
some_func();
}