How to call functor form the thread

Yes, It is possible to call functor from thread.

What is functor?

Functor is not function, is it a case where operator () is overloaded therefore object itself act as function or function pointer as per usage in code.

Let's check the code where we are trying to modify value of member variable m_value using functor.


#include<iostream>

#include <thread>
#include<string>
using namespace std;

class Suggest
{
    string m_value;
public:
    Suggest()
    {
        cout<<"Constructor(default) :: Called"<<endl;
        m_value="Default Suggestion Given";
    }
    Suggest(string str)
    {
        cout<<"Constructor(string) :: Called"<<endl;
        m_value=str;
    }

    //functor i.e. overloaded () operator
    //By which objects shall be treated as function & function pointer.

    void operator()()
    {
        cout<<"Functor :: Called - New Value added "<<endl;
        this -> m_value="Universal Suggestion Given";
    }
    void display()
    {
        cout<<"Suggestion:: "<<m_value<<endl;
    }
};

int main()
{

    Suggest sObj;
    sObj.display();

    cout<<"\nFUNCTOR - Call:: No object data changed"<<endl;
    //FUNCTOR - Call with thread()
    //Important:: No object data changed.

    std::thread objThrd(sObj);
    objThrd.join();
    sObj.display();

    cout<<"\nFUNCTOR - Call:: using lambda with std::thread"<<endl;
    //one way to change data-member of object
    //FUNCTOR - Call using lambda with std::thread

    std::thread objThrd1([&sObj](){sObj();});
    objThrd1.join();
    sObj.display();

    return 0;
}


Compile:g++ functor.cpp -o functor -lpthread

Output:./functor


Constructor(default) :: Called
Suggestion:: Default Suggestion Given


FUNCTOR - Call:: No object data changed
Functor :: Called - New Value added
Suggestion:: Default Suggestion Given

FUNCTOR - Call:: using lambda with std::thread
Functor :: Called - New Value added
Suggestion:: Universal Suggestion Given



PREV:: How to call overloaded member function from thread

Your Comments /Suggestions & Questions are always welcome. 

We would like to help you with best of our knowledge.

So feel free to put Questions

No comments:

Post a Comment