zoukankan      html  css  js  c++  java
  • c++11多线程---std::ref和std::cref

    std::ref和std::cref
     
    解释
    std::ref 用于包装按引用传递的值。
    std::cref 用于包装按const引用传递的值。
     
    为什么需要std::ref和std::cref
    bind()是一个函数模板,它的原理是根据已有的模板,生成一个函数,但是由于bind()不知道生成的函数执行的时候,传递进来的参数是否还有效。所以它选择参数值传递而不是引用传递。如果想引用传递,std::ref和std::cref就派上用场了。
     
    #include <functional>
    #include <iostream>
    
    void f(int& n1, int& n2, const int& n3)
    {
        std::cout << "In function: n1[" << n1 << "]    n2[" << n2 << "]    n3[" << n3 << "]" << std::endl;
        ++n1; // 增加存储于函数对象的 n1 副本
        ++n2; // 增加 main() 的 n2
        //++n3; // 编译错误
        std::cout << "In function end: n1[" << n1 << "]     n2[" << n2 << "]     n3[" << n3 << "]" << std::endl;
    }
    
    int main()
    {
        int n1 = 1, n2 = 1, n3 = 1;
        std::cout << "Before function: n1[" << n1 << "]     n2[" << n2 << "]     n3[" << n3 << "]" << std::endl;
        std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
        bound_f();
        std::cout << "After function: n1[" << n1 << "]     n2[" << n2 << "]     n3[" << n3 << "]" << std::endl;
    }
    #include <iostream>
    #include <thread>
    #include <mutex>
    
    void inc(std::mutex &mutex, int loop, int &counter) {
        for (int i = 0; i < loop; i++) {
            mutex.lock();
            ++counter;
            mutex.unlock();
        }
    }
    int main() {
        std::thread threads[5];
        std::mutex mutex;
        int counter = 0;
    
        for (std::thread &thr: threads) {
            thr = std::thread(inc, std::ref(mutex), 1000, std::ref(counter));
        }
        for (std::thread &thr: threads) {
            thr.join();
        }
    
        // 输出:5000,如果inc中调用的是try_lock,则此处可能会<5000
        std::cout << counter << std::endl;
    
        return 0;
    }
  • 相关阅读:
    对于Spring使用注解的一点总结
    2014-01-12
    Struts2补充a
    2014从Struts2开始
    总结:XHTML中链接CSS的四种方法(笔记)
    XHTML
    我Web前端开发的开端
    踏上前端路
    调取手机相册和拍照功能js
    mac常用系统指令和终端指令总结
  • 原文地址:https://www.cnblogs.com/lovebay/p/11579909.html
Copyright © 2011-2022 走看看