栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/867019.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号