[英]Is it legal to pass `std::shared_future` as a reference to functions?
Passing std::shared_future
by value is legal, since std::shared_future
is copyable.按值传递
std::shared_future
是合法的,因为std::shared_future
是可复制的。
#include <future>
#include <vector>
#include <iostream>
int factorial(std::shared_future<int> sf)
{
int res = 1;
int num = sf.get();
for(int i=num; i>1; i--)
{
res *= i;
}
return res;
}
int main()
{
std::promise<int> prs;
std::vector<std::future<int>> vec;
std::shared_future<int> sf{prs.get_future()};
for(int i=0; i<10; i++)
{
vec.push_back(std::async(std::launch::async, factorial, sf));
}
prs.set_value(5);
for(auto& fut: vec)
{
std::cout << fut.get() << std::endl;
}
}
Is it legal to pass std::shared_future
as a reference to functions?将
std::shared_future
作为对函数的引用传递是否合法?
#include <future>
#include <vector>
#include <iostream>
int factorial(std::shared_future<int>& sf)
{
int res = 1;
int num = sf.get();
for(int i=num; i>1; i--)
{
res *= i;
}
return res;
}
int main()
{
std::promise<int> prs;
std::vector<std::future<int>> vec;
std::shared_future<int> sf{prs.get_future()};
for(int i=0; i<10; i++)
{
vec.push_back(std::async(std::launch::async, factorial, std::ref(sf)));
}
prs.set_value(5);
for(auto& fut: vec)
{
std::cout << fut.get() << std::endl;
}
}
The code snippet compiles and seems work well.代码片段编译并且看起来运行良好。 Could somebody shed some light on this mattter?
有人可以阐明这个问题吗?
UPDATED :更新:
For shared_ptr
, many aspects need to be considered when choosing to passing as a reference or passing by value.对于
shared_ptr
,在选择作为引用传递或按值传递时需要考虑许多方面。
What about shared_future
? shared_future
呢? How to make the choice?如何做出选择?
From cppreference :来自cppreference :
Calling wait on the same
std::shared_future
from multiple threads is not safe;从多个线程对同一个
std::shared_future
调用 wait 是不安全的; the intended use is for each thread that waits on the same shared state to have a copy of astd::shared_future
.预期用途是让等待同一个共享 state 的每个线程都拥有
std::shared_future
shared_future 的副本。
A shared_future
is already behaving like a "reference" to some shared state. However, its intended use is that each thread uses its own copy, such that they can call wait
and other methods without getting into their way. shared_future
已经表现得像是对某些共享 state 的“引用”。但是,它的预期用途是每个线程都使用自己的副本,这样它们就可以调用wait
和其他方法而不会妨碍它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.