c++ – Synchronization in boost::asio::thread_pool to return the best result
I have an async function where I need to return the best result (chain with maximum score) from results (other chains and them scores) computed in async threads in boost::asio::thread_pool.
As I need to return only one chain, handling other chains outside the thread pool is not required, and as I understand I just need to synchronize the place there the max_score and best_chain are computed.
#include
#include
#include
#include
#include
int GetBestChainAsync(const std::vector<:vector>>& data)
{
std::vector best_chain;
int n{5};
float max_score{};
std::mutex mutex;
boost::asio::thread_pool pool(n);
for (int i = 0; i < n; i++) {
boost::asio::post(pool, [&best_chain, &data, &max_score, &mutex, i]() {
std::vector chain = GetChain(data, i);
float score = SimilarityScore(chain, data);
std::scoped_lock lock(mutex);
if (score > max_score) {
max_score = score;
best_chain = chain;
}
});
}
pool.join();
for (const auto& c: best_chain) {
std::cout << c << std::endl;
}
}
Is this logic correct?
Is it possible to somehow to use the asio::strand here instead of std::mutex and simplify function?
Read more here: Source link
