How to Call function with Reference Variable, Default Argument and Pointer Variable from thread.

Yes it is possible to call a function with arguments from a thread object.

NOTE:(1)- Arguments to thread function shall either be moved (std::move) or call by value. If we have any reference variable as a argument then it shall be called with std::ref or std::cref.

NOTE:(2)- Return value of function shall be ignored, as thread won't allow function to return value. there are other methods to return value from thread like future and promise.

NOTE:(3)- If the function have default argument and that default argument shall be passed explicitly to thread call (constructor). Default Arguments shall be automatically deducted by compiler, shall generate following error. Or use Lambda function as a work around.

Let check with an example.

 

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

//taskFunc with multiple Argument
void taskFunc(int arg1, int* arg2, int& arg3, bool defaultArg=true)
{
    cout<<"called:: taskFunc(int arg1, int* arg2, int& arg3,bool defaultArg=true)"<<endl;
    cout<<"called:: taskFunc()arg1="<<arg1<<" arg2="<<(++(*arg2)) <<" arg3="<<++arg3<<" default="<<defaultArg<<endl;
}
int main()
{

    //Array of threads
    std::thread threadPool[2];

    int arg1=1, arg2=2000, arg3=3000;

    //Assign task to already existing thread Object.
    cout<<"Assign task to Array of threads --threadPool[0] "<<endl;

    threadPool[0]=     std::thread(taskFunc,arg1,&arg2,std::ref(arg3),true);
    threadPool[0].join();

    cout<<"After:: taskFunc()arg1="<<arg1<<" arg2="<<arg2<<" arg3="<<arg3<<endl;

    //Assign task to already existing thread Object.
    cout<<endl<<"Assign task to Array of threads --threadPool[1] with lambda function"<<endl;
    auto lmbdaFunc=[](int arg1, int* arg2, int& arg3){
            taskFunc(arg1,arg2,arg3);
    };

    threadPool[1]=std::thread(lmbdaFunc,arg1,&arg2,std::ref(arg3));
    threadPool[1].join();

    cout<<"After:: taskFunc()arg1="<<arg1<<" arg2="<<arg2<<" arg3="<<arg3<<endl;
    return 0;
}
 

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


Output: ./thread

Assign task to Array of threads --threadPool[0]
called:: taskFunc(int arg1, int* arg2, int& arg3,bool defaultArg=true)
called:: taskFunc()arg1=1 arg2=2001 arg3=3001 default=1
After:: taskFunc()arg1=1 arg2=2001 arg3=3001

Assign task to Array of threads --threadPool[1] with lambda function
called:: taskFunc(int arg1, int* arg2, int& arg3,bool defaultArg=true)
called:: taskFunc()arg1=1 arg2=2002 arg3=3002 default=1
After:: taskFunc()arg1=1 arg2=2002 arg3=3002

 



PREV:: std::thread::detch() [Advanced]



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