我如何使用boost.lambda与boost.thread得到线程的返回值? [英] How do I use boost.lambda with boost.thread to get the thread's return value?

查看:565
本文介绍了我如何使用boost.lambda与boost.thread得到线程的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做这样的事情:

 使用空间boost ::拉姆达;
使用boost ::线程;加INT(INT A,INT B){返回A + B;}INT总和,X = 2,Y = 6;
螺纹加法器(VAR(总和)=添加(_1,_2),X,Y);
adder.join();
COUT<<和;

我得到一个编译错误:


  

无法从的boost :: ARG'到'廉政'

转换参数1

解决方案

您是非常接近实际!问题是,你直接调用Add()方法和λ的占位符,它没有被评估懒洋洋地在lambda里面,但马上。

下面是一个固定的版本:

 使用空间boost ::拉姆达;
使用boost ::线程;INT总和,X = 2,Y = 6;
螺纹加法器(VAR(总和)= _1 + _2,X,Y);
adder.join();
COUT<<和;

如果你真的想使用添加函数,你会使用绑定

 使用空间boost ::拉姆达;
使用boost ::线程;加INT(INT A,INT B){返回A + B;}INT总和,X = 2,Y = 6;
螺纹加法器(VAR(总和)=绑定(添加,_1,_2),X,Y);
adder.join();
COUT<<和;

I'm trying to do something like this:

using namespace boost::lambda;
using boost::thread;

int add(int a, int b) {return a+b;}

int sum, x=2, y=6;
thread adder(var(sum) = add(_1, _2), x, y);
adder.join();
cout << sum;

I get a compile error:

cannot convert parameter 1 from 'boost::arg' to 'int'

解决方案

You’re really close actually! The problem is that you’re directly calling add() with Lambda’s placeholders—it’s not being evaluated lazily inside the lambda, but right away.

Here’s a fixed version:

using namespace boost::lambda;
using boost::thread;

int sum, x=2, y=6;
thread adder(var(sum) = _1 + _2, x, y);
adder.join();
cout << sum;

And if you really want to use the add function, you'd use bind:

using namespace boost::lambda;
using boost::thread;

int add(int a, int b) {return a+b;}

int sum, x=2, y=6;
thread adder(var(sum) = bind(add, _1, _2), x, y);
adder.join();
cout << sum;

这篇关于我如何使用boost.lambda与boost.thread得到线程的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆