Functionality of void operator()()

前端 未结 4 610
一生所求
一生所求 2021-02-01 05:11

I am confused about the functionality of void operator()().

Could you tell me about that, for instance:

class background_task
{
public:

            


        
4条回答
  •  日久生厌
    2021-02-01 05:34

    All the hints that were contributed above are correct to sequential programs, I mean, programs without threads. Using threads things change. First of all, by default parameters to std::thread are functions and functions parameters. Probably you were studying the book "C++ concurrency in action", and the author shows an interesting example:

    void do_some_work(); 
    thread my_thread(do_some_work); //thread receives the function address
    

    Suppose this function:

    void do_other_job(int k); In the body of the code, you should do:

    k=3; 
    thread my_thread2(do_other_job, k); 
    

    in order to spawn another thread.

    So, using threads the compiler interprets f ( in std::thread my_thread(f);) by default as a function instead of a class. To change that you have to initiate an operator() to warn the compiler you are working with a class. An alternative code could be:

    class background_task{
    public: 
    background_task(){
     do_sth(); 
     do_sth_else(); 
     }
    void operator()(){} 
    }; 
    background_task f; 
    thread mythread10(f);
    

    Eventually, it's not correct, using threads, feeding the operator, so this code doesn't work:

    void operator()(int x){
    do_sth(); 
    cout<<"x = "<

    It happens because all the code inside the brackets are read-only, and cannot be changed during the run-time. If you aim to insert a variable in the constructor, it must be put in the thread initialization. So:

    class backg{
    public: 
    backg(int i){
       do_sth(i); 
       }
    void operator()(){}
    }; 
    int main(){
    thread mythread{ backg(12) }; //using c++11
    return 0; 
    }
    

    Will run without mistakes, and will perform the function do_sth(12) in the thread spawned.

    I hope I have helped.

提交回复
热议问题