如何处理动态数量的线程资源



我有一个模板类别,其中多个线程具有自己的变量副本(缓冲,静音,条件 - 变量)。

template<size_t N> // N = number of threads
class Foo
{
private:
    void thread_job(const int id);
    std::vector<std::thread> threads; // initialized via push_back(std::thread)
    std::string thread_buffer[N];
    std::mutex mu[N];
    std::condition_variable cond[N];
};

我理解这些变量是单独对象的集合,因此线程可以为特定元素获取锁,而不会干扰他人:

void Foo<N>::thread_job(const int id)
{
    std::lock_guard<std::mutex> locker{mu[id]};
    thread_buffer[id].swap(input_buffer);
    cond[id].notify_one();
}

假设我想远离定义编译时的线程数,而是将与线程相关的变量存储在动态容器中,例如std :: vector。线程在访问其元素之一之前必须锁定整个容器?

如果是这样,您是否有有关如何避免此问题的建议?我只能想到创建比想象使用并坚持数组方法的元素更多的数组,例如:

std::string thread_buffer[64];
std::mutex mu[64];
std::condition_variable cond[64];

线程必须在访问一个容器之前锁定整个容器 它的元素?

否,只要您可以保证另一个线程不会同时修改所述容器。

最新更新