【发布时间】:2018-10-19 11:39:09
【问题描述】:
我正在尝试通过随机线性网络编码 (RLNC) 使用多线程进行编码以提高性能。
但是,我遇到了性能问题,我的多线程解决方案速度较慢,比当前的非线程版本慢得多。我有一个暂停,它是 m_completed 上的 atomic 访问和用于将元素插入到 m_results 的 std::mutex 正在扼杀我的表现。但是,我不知道如何确认这一点。
所以更多信息函数completed() 在主线程while(!encoder.completed()){} 的while-loop 中被调用,这会导致大量的原子访问,但我找不到合适的方法来做它没有原子或互斥锁。您可以在下面找到代码。
所以,如果有人可以看到错误或指导我找到更好的方法,我会非常满意。我花了 1.5 周的时间找出问题所在,我唯一的想法是 atomic 或 std::mutex locks
#include <cstdint>
#include <vector>
#include <mutex>
#include <memory>
#include <atomic>
...
namespace master_thesis
{
namespace encoder
{
class smart_encoder
{
...
void start()
{
...
// Incase there are more an uneven amount
// of symbols we adjust this abov
else
{
m_pool.enqueue([this, encoder](){
std::vector<std::vector<uint8_t>> total_payload(this->m_coefficients,
std::vector<uint8_t>(encoder->payload_size()));
std::vector<uint8_t> payload(encoder->payload_size());
for (uint32_t j = 0; j < this->m_coefficients; ++j)
{
encoder->write_payload(payload.data());
total_payload[j] = payload; //.insert(total_payload.begin() + j, payload);
}
this->m_mutex.lock();
this->m_result.insert(std::end(this->m_result),
std::begin(total_payload),
std::end(total_payload));
++(this->m_completed);
this->m_mutex.unlock();
});
}
}
}
bool completed()
{
return m_completed.load() >= (m_threads - 1);
}
std::vector<std::vector<uint8_t>> result()
{
return m_result;
}
private:
uint32_t m_symbols;
uint32_t m_symbol_size;
std::atomic<uint32_t> m_completed;
unsigned int m_threads;
uint32_t m_coefficients;
std::mutex m_mutex;
std::vector<uint8_t> m_data;
std::vector<std::vector<uint8_t>> m_result;
ThreadPool m_pool;
std::vector<std::shared_ptr<rlnc_encoder>> m_encoders;
};
}
}
【问题讨论】:
-
在没有争用的情况下两者都很快。
-
而不是像那样循环 - 使用条件变量。
-
@stark 但问题是两者都可能存在争用,至少我能做到
-
移动而不是复制,同时将
insert保持在互斥区域内,请参阅here。
标签: c++ multithreading performance