传递引用变量到thread的方法

为了加速运行一个c++程序,我们常常会用到multiple thread编程。比如下面是一个例子:

#include <thread>

#include <iostream>


void message(std::string& msg){

std::cout<<msg<<std::endl;

msg = "Hello World!";

}


int main(){

std::string msg = "Love the World!";

std:thread t1(message, msg);

t1.join(); //main wait for t1 to finish

std::cout<<msg<<std::endl;

return 0;

}

运行上述程序之后,我们会发现,屏幕上两次输出的消息都是"Love the World!"。原因是,对于线程来说,总是按照传递值的方式来调用函数。所以,在线程中的函数中改变msg的值不会改变主函数中的msg值。

如果需要在线程中使用传递引用的方式调用函数,可以将std:thread t1(message, msg);改为std:thread t1(message, std::ref(msg));。修改之后在运行程序,两次的消息就不同了!


另外,使用std::move(msg)也可以达到相同的效果,而且可以避免data race。 std::move()函数还可以将一个线程转移到另一个线程,例如:

std::thread t1(fun1,std::move(v1),std::move(v2),...);

//wrong style: std::thread t2 = t1; which will not complie

std::thread t2 = std:::move(t1); //now t1 is empty 

t2.join();

...


另外,由于多线程的并行,我们可能会遇到多个线程访问同一的数据的情况。比如,对一幅图像,同时进行人脸检测和眼部检测,都需要用到这一福图像。最直接的解决方案是为每一个线程单独创建一份数据备份。当然,这带来的是数据拷贝的损耗。所以,我们需要另辟蹊径,寻找更好的方法。这时我们就需要用到mutex,如下:

#include <mutex>

...

std::mutex mu;

share_print(std::string msg, int id){

std::lock_guard<std::mutex> locker(mu);

std::cout<<msg<<id<<std::endl;

}

当我们运行此函数时,不会出现两个线程同时占用cout而出现数据竞争的情况。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值