在不使用 Boost::p Romise 的情况下在 boost 线程中返回值
return value in boost thread without using boost::promise
int xxx()
{
return 5;
}
int main()
{
boost::thread th;
th = boost::thread(xxx);
th.join();
return 0;
}
如何在不使用 boost::p romise 的情况下捕获 xxx() 方法返回的值?
既然你说你不能改变xxx
,调用另一个函数,将结果放在可访问的地方。承诺可能仍然是最好的选择,但如果你小心同步,你可以直接将其写入局部变量。例如
int result;
th = boost::thread([&]{result = xxx();});
// Careful! result will be modified by the thread.
// Don't access it without synchronisation.
th.join();
// result is now safe to access.
如注释中所述,有一个方便的async
函数,它为您提供了一个从中检索异步调用函数的返回值的未来:
auto future = boost::async(boost::launch::async, xxx);
int result = future.get();
实际上我想在 main 中更改某些内容并且方法 xxx() 不可编辑
使用具有适当同步的共享对象(互斥锁、互斥锁+条件变量)
我提到的选项的采样器(显然,您不需要所有这些选项):
int global = -1;
std::mutex mtx;
std::condition_variable cv;
void xxx()
{
// do lot of work...
{
std::unique_lock<std::mutex> lk(mx);
global = 5; // safe because lock for exclusive access
cv.notify_all();
}
}
int main()
{
boost::thread th(xxx);
{
// need to lock since the thread might be running
// this might block until `global` is actually set
std::unique_lock<std::mutex> lk(mx);
cv.wait(lk, [] { return global != -1; });
std::cout << "global has been set: " << global << "n";
}
th.join();
// here there is no locking need
return global;
}
相关文章:
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- (如何)我可以在不安装完整的提升库的情况下使用 boost::spirit X3 吗?
- 如何在没有(constexpr)实例的情况下反省到boost::hana::map<...>?
- 在使用 boost 共享互斥体时,我应该在什么情况下使用 owns_lock() 函数
- 为什么在这种情况下 boost::recursive_wrapper 不起作用
- -std=c++0x 导致在 boost 1.64 的情况下返回对临时的引用
- Boost Filesystem flowly_caronical不会在没有父文件夹的情况下解决相对路径
- 我如何在不启用例外的情况下构建Boost 1.70.0
- 如何在不重新索引顶点的情况下调用"boost::remove_vertex"?
- 如何在不使用Boost的情况下重写此代码
- 在 boost::lockfree:queue 默认构造函数的情况下断言失败
- 在存在分配器重新启动的情况下,使用null_mutex Safe是boost :: fast_pool_allocato
- 如何在不打开的情况下创建带有 boost 文件系统的文件
- 如何使用 boost 在不打开串行端口的情况下创建串行端口
- 在不使用boost覆盖整个ini的情况下写入ini文件值
- 如何 在没有 Boost 的情况下将 C++ 成员函数作为线程执行
- 在没有ICU或boost的情况下规范化C++中的unicode字符
- 如何在不使用windows.h或Boost的情况下在Visual C++9.0中获得毫秒分辨率
- boost::p rogram_options:如何在没有"--"或"-"的情况下指定命令
- boost::asio::async_read在不满足完成条件的情况下结束