2、 Passing functions to thread functions

Time:2021-5-9
#include<thread>
void fun(int i,std::string const& str) {
    return;
}

int main()
{
    std::string s("hellos");
    std::thread t(fun,3,s);
    t.join();
    system("pause");
    return 0;
}

Pass parameters to the function, and the default parameters will be changedBe copiedIn the thread’s independent memory, all accesses in the function are copied copies, even if the parameters are in the form of references. For example, a copy of s will be generated above and then assigned to STR, which is not a reference of S.

How to pass a non constant reference?

void fun(int i,std::string & str);
std::thread t(fun,3,s);

The second parameter of the fun function expects to pass in a reference, but the constructor of STD:: thread is unknown; The constructor ignores the expected parameter type of the function and blindly copies the provided variable s. However, in the code, the parameters will be copied and passed in the form of right value to take care of those types that can only be moved, and then the parameters will be passed to the fun function with the right value as the parameter. Because the function expects a non constant reference as a parameter instead of a right value, it willError compiling. For developers who are familiar with STD:: bind, the solution to the problem is obvious: you can use STD:: ref to convert the parameters to the form of references. It can be called correctly as follows:

void fun(int i,std::string & str);
std::thread t(fun,3,std::ref(s));

Pass constant reference:

void fun(int i,std::string const& str);
std::thread t(fun,3,std::ref(s));
void fun(int i,std::string const& str);
std::thread t(fun,3,std::cref(s));

Both of the two methods explicitly refer to and pass when constructing threads, and add const permission to the function parameters of fun, so that STR cannot be modified in fun.

Wrong writing:

void fun(int i,std::string & str);
std::thread t(fun,3,std::cref(s));

This way of writing will be used in the futureError compilingWhen constructing a thread, the constant reference is explicitly passed. However, if you do not add const permission to the parameter of the fun function, an error will be reported if you pass a constant to a non const variable.

Using class function as thread function

 class A
 {
 public:
      fun(int i);
 };
A a;
std::thread t(&A::fun,&a,1); 

The new thread takes a.fun() as the thread function (note that it must be a public function); The address of a is provided to the function as a pointer object. The third parameter of the thread constructor is the first parameter of the member function, and so on.