c++ ref在thread和bind中的使用

c++ ref在thread和bind中的使用,第1张

std::ref对std::thread

std::mutex删除了拷贝构造函数。构造std::thread时,给线程函数传参时默认采用的是值传递(即使线程函数的入参为引用形式,这样设计应该时考虑到多个线程同时引用一个变量时的生命周期安全问题吧), 所以被传参数对应的是含有mutex成员的类的实例时,编译不通过,需要使用std::ref。

#include 
#include 
#include 
#include 

class A {
public:
    std::mutex _mtx;
};
void threadFunc(A& obj) {

}
int main() {
    A objA;

    // compile error:
    //std::thread t1(threadFunc, objA); // error C2664: “std::tuple::tuple(....

    // Ok:
    std::thread t1(threadFunc, std::ref(objA));
    
    if (t1.joinable()) {
        t1.join();
    }
    return 0;
}

上例,用了引用则需要注意objA的生命周期,因为其可能在主线程被销毁,t1如果detach的话会产生问题,所以还是直接用 std::shared_ptr更好 :)

class A {
public:
    std::mutex _mtx;
};
void threadFunc(std::shared_ptr obj) {

}
int main() {

    std::shared_ptr objA = std::make_shared();
    std::thread t1(threadFunc, objA);

    if (t1.joinable()) {
        t1.join();
    }
    return 0;
}

std::ref对std::bind

myFunc的入参虽然为引用类型,但是如果在std::bind时,不使用ref,仍然按照值传递方式。

#include 
#include 
#include 
#include 
void myFunc(int& a1, int& a2) {
    std::cout << "a1=" << a1 << " a2=" << a2 << std::endl;
    a1 = 100;
    a2 = 200;
}

int main() {
    int a1 = 1;
    int a2 = 2;
    //std::function bound_f = std::bind(myFunc, a1, a2);//After func, a1=1 a2=2
    std::function bound_f = std::bind(myFunc, std::ref(a1), std::ref(a2));//After func, a1=100 a2=200
    bound_f();
    std::cout << "After func, a1=" << a1 << " a2=" << a2 << std::endl;

    return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/874770.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-13
下一篇2022-05-13

发表评论

登录后才能评论

评论列表(0条)

    保存