gpt4 book ai didi

arrays - 如何处理动态数量的线程拥有的资源

转载 作者:行者123 更新时间:2023-12-03 13:04:55 24 4
gpt4 key购买 nike

我有一个模板化的类,其中多个线程拥有自己的变量副本(缓冲区,互斥对象,条件变量)。

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];

最佳答案

Would a thread have to lock the whole container before accessing one of its elements?



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

关于arrays - 如何处理动态数量的线程拥有的资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21357886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com