vector<int> vecCustomers;
// populate vecCustomers
void funA()
{
std::lock_guard<std::mutex> guard( _mutex ); // need lock here
for(int i=0; i<vecCustomers.size(); ++i)
{
funB( vecCustomers[i] ); // can I run this asynchronously
}
}
void funB(int i)
{
// do something here
}Question> funA访问关键资源,并使用锁保护资源。funB不使用任何关键资源,也不需要互斥。是否有一种方法可以利用std::async来调用funB并立即返回以准备循环中的下一个funB调用?此外,在函数返回之前,funB的所有任务都必须完成。
谢谢
==更新==
我根据建议编写了以下代码。现在,新的问题是为什么所有线程都被第一个线程阻塞?
输出总是如下:
From[0]:H0 << why this thread blocks all others?
From[1]:H1
From[2]:H2
From[3]:H3
From[4]:H4
#include <vector>
#include <future>
#include <mutex>
#include <string>
#include <iostream>
#include <chrono>
using namespace std;
struct ClassA
{
ClassA()
{
vecStr.push_back( "H0" );
vecStr.push_back( "H1" );
vecStr.push_back( "H2" );
vecStr.push_back( "H3" );
vecStr.push_back( "H4" );
}
void start()
{
for ( int i = 0; i < 5; ++i )
{
std::unique_lock<std::mutex> guard( _mutex );
std::string strCopy = vecStr[i];
guard.unlock();
std::async( std::launch::async, &ClassA::PrintString, this, i, strCopy );
//PrintString( i, vecStr[i] );
guard.lock();
}
}
void PrintString( int i, const string& str) const
{
if ( i == 0 )
std::this_thread::sleep_for( std::chrono::seconds( 10 ) );
cout << "From[" << i << "]:" << str << endl;
}
mutex _mutex;
vector<string> vecStr;
};
int main()
{
ClassA ca;
ca.start();
return 0;
}===Update 2===
#include <vector>
#include <future>
#include <mutex>
#include <string>
#include <iostream>
#include <chrono>
using namespace std;
struct ClassA
{
ClassA()
{
vecStr.push_back( "H0" );
vecStr.push_back( "H1" );
vecStr.push_back( "H2" );
vecStr.push_back( "H3" );
vecStr.push_back( "H4" );
}
void start()
{
std::vector<std::future<void>> result;
for ( int i = 0; i < 5; ++i )
{
std::unique_lock<std::mutex> guard( _mutex );
std::string strCopy = vecStr[i];
guard.unlock();
result.push_back( std::async( std::launch::async, &ClassA::PrintString, this, i, strCopy ) );
//PrintString( i, vecStr[i] );
}
for(auto &e : result)
{
e.get();
}
}
void PrintString( int i, const string& str) const
{
static std::mutex m;
std::unique_lock<std::mutex> _(m);
if ( i == 0 )
{
cout << "From[" << i << "]:" << str << " sleep for a while" << endl;
_.unlock();
std::this_thread::sleep_for( std::chrono::seconds( 10 ) );
}
else
cout << "From[" << i << "]:" << str << endl;
}
mutex _mutex;
vector<string> vecStr;
};
int main()
{
ClassA ca;
ca.start();
return 0;
}发布于 2016-04-29 16:55:10
您看到按顺序执行的调用的主要原因是您没有以任何方式利用并行性(等等,什么?)但是)。让我解释一下
std::async不只是启动一个要异步运行的任务,它还返回一个std::future,该std::future可以用于获取返回的值(如果已启动的函数返回某些内容)。但是,由于您没有存储未来,它将在任务启动后立即销毁。对于您来说,不幸的是,在这种情况下,析构函数阻塞直到调用完成。
如果以下所有内容都为真,则可能会阻塞:共享状态是通过调用std::异步创建的,共享状态尚未准备好,这是对共享状态的最后一次引用。
(报价)由于这一事实,许多人表达了失望,但这正是标准所规定的。
因此,您需要做的是将std::future(在向量或其他地方)存储起来,直到全部启动为止。
发布于 2016-04-28 16:52:33
当然,您可以在保持互斥锁的同时调用std::async。缺点是调用std::async需要一些时间,从而增加锁定互斥锁的时间,从而减少并行性。
在保持锁的同时复制该矢量可能会更便宜。然后释放互斥体并异步处理副本。
您的优化目标是最小化互斥锁的时间,以及可能在函数中花费的时间。
https://stackoverflow.com/questions/36920579
复制相似问题