• boost和std中的thread的引用参数


    boost 1.60.0

    先上代码:

     1 #include <boost/thread.hpp>
     2 #include <iostream>
     3 
     4 void add(int &i)
     5 {
     6     std::cout<<"in  add, befor ++i, i: "<<i<<std::endl;
     7     ++i;
     8     std::cout<<"in  add, after ++i, i: "<<i<<std::endl;
     9 }
    10 
    11 int main()
    12 {
    13     int i = 1;
    14     std::cout<<"in main, befor add, i: "<<i<<std::endl;
    15     boost::thread thre(add, i);
    16     thre.join();
    17     std::cout<<"in main, after add, i: "<<i<<std::endl;
    18     std::cin.get();
    19 }

    结果:

    in main, befor add, i: 1
    in  add, befor ++i, i: 1
    in  add, after ++i, i: 2
    in main, after add, i: 1

    可以看到虽然函数形参是引用方式,但线程并没有改变主函数中的变量。

    将第15行代码改为

    15 boost::thread thre(add, boost::ref(i));

    后,输出:

    in main, befor add, i: 1
    in  add, befor ++i, i: 1
    in  add, after ++i, i: 2
    in main, after add, i: 2

    可以推测:thread启动函数时,使用和bind一样的方式进行参数绑定。虽然形参是引用方式,但是如果不使用ref(),结果依然是值传递。

    C++11

    而在C++ std中,前一种调用方式会引发编译错误。如果确实有这种需求,可以借助bind函数:

     1 #include <iostream>
     2 #include <thread>
     3 
     4 void add(int &i) {
     5     std::cout<<"in  add, befor ++i, i: "<<i<<std::endl;
     6     ++i;
     7     std::cout<<"in  add, after ++i, i: "<<i<<std::endl;
     8 }
     9 
    10 
    11 int main()
    12 {
    13     int i = 1;
    14     std::cout<<"in main, befor add, i: "<<i<<std::endl;
    15     auto func = std::bind(add, i);
    16     std::thread thre(func); // or std::thread thre(add, std::ref(i));
    17     thre.join();
    18     std::cout<<"in main, after add, i: "<<i<<std::endl;
    19     std::cin.get();
    20 }
  • 相关阅读:
    数组的操作方法
    数组遍历的方法以及区别
    组件内的守卫
    路由守卫
    软件工程
    java web (j2ee)学习路线 —— 将青春交给命运
    团队作业(一)- 第五组
    软件工程
    软件工程-第二次作业
    java局部/成员/静态/实例变量
  • 原文地址:https://www.cnblogs.com/kohlrabi/p/6070062.html
Copyright © 2020-2023  润新知