1

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();
    }
chtz
  • 17,329
  • 4
  • 26
  • 56
Anand Kulkarni
  • 395
  • 1
  • 2
  • 10

1 Answers1

0

The problem is that both lines you commented out are actually function declarations (see e.g., this question).

The solution is to write either of these

ScopedThread t{std::thread(func(some_local_state))};
ScopedThread t((std::thread(func(some_local_state))));
ScopedThread t{std::thread(my_func)};
ScopedThread t((std::thread(my_func)));
chtz
  • 17,329
  • 4
  • 26
  • 56
  • Maybe also check this one: https://stackoverflow.com/questions/6939986/c-nested-constructor-calls-vs-function-declaration – chtz Jun 10 '17 at 10:35