Search code examples
c++boost-thread

void operator()() understanding


I am learning how to use thread in boost library, during my search I found the code below:

struct count
{
    count(int id) : id(id) {}

    void operator()()
    {
         for (int i = 0; i < 10; ++i)
         {
             boost::mutex::scoped_lock
             lock(io_mutex);
             std::cout << id << ": " << i << std::endl;
         }
    }
    int id;
};

int main(int argc, char* argv[])
{
    boost::thread thrd1(count(1));
    boost::thread thrd2(count(2));

    thrd1.join();
    thrd2.join();
    return 0;
}

This program works fine, but my question is, what is the behaviour of the void operator()() function? Because there are two threads and each one initializes the count with different values. It's two main count variables are created seperately, so their void operator()() should be different for each variable. But it seems that void operator()() is the same for both threads. One more thing in this code void operator()() is not being called from anywhere, so how it is running?

Can someone please explain me what is going on inside this function?

void operator()() 

Solution

  • This is a tricky syntax here.

    boost::thread thrd1(count(1));
    boost::thread thrd2(count(2));
    

    In those two lines, the operator() is NOT called directly. The count(n) visible here is the constructor. Then, the objects constructed with '1' and '2' values are passed to a thread objects, which then internally calls operator() to run the specific task on that different thread created for this purpose.

    But since two objects remembered different values (1/2) in their ctors, the common code in operator() operates on different actual values of id field. That's why the operator has no parameters: all required params are stored in the 'count' object during its construction.

    Btw. to construct an object and call the operator(), a line would look like this:

    count(1)();