gpt4 book ai didi

c++ - 我应该创建多少个线程?

转载 作者:行者123 更新时间:2023-11-30 03:57:27 27 4
gpt4 key购买 nike

基于 this问题,我有一个类,它的构造函数只做一些赋值,然后有一个 build() 成员函数实际完成这项工作。

我知道我必须构建的对象数量在 [2, 16] 范围内。实际数字是用户参数。

我在这样的 for 循环中创建我的对象

for (int i = 0; i < n; ++i) {
roots.push_back(RKD<DivisionSpace>(...));
}

然后在另一个 for 循环中创建线程。每个线程都根据以下逻辑在对象 block 中调用 build():

If your vector has n elements and you have p threads, thread i writes only to elements

[i n / p, (i + 1) n / p).

那么比如情况是这样的:

std::vector<RKD<Foo>> foos;
// here is a for loop that pushes back 'n' objects to foos

// thread A // thread B // thread C
foos[0].build(); foos[n / 3 + 0].build(); foos[2 * n / 3 + 0].build();
foos[1].build(); foos[n / 3 + 1].build(); foos[2 * n / 3 + 1].build();
foos[2].build(); foos[n / 3 + 2].build(); foos[2 * n / 3 + 2].build();
... ... ...

我遵循的方法是确定线程数p,如下所示:

p = min(n, P) 

其中 n 是我要创建的对象数,Pstd::thread::hardware_concurrency 的返回值.在dealing之后对于 C++11 特性存在的一些问题,我阅读了以下内容:

Even when hardware_concurrency is implemented, it cannot be relied as a direct mapping to the number of cores. This is what the standard says it returns - The number of hardware thread contexts. And goes on to state - This value should only be considered to be a hint If your machine has hyperthreading enabled, it's entirely possible the value returned will be 2x the number of cores. If you want a reliable answer, you'll need to use whatever facilities your OS provides. – Praetorian

这意味着我可能应该改变方法,因为这段代码要由多个用户执行(我的意思是不仅在我的系统中,很多人都会运行该代码)。因此,我想以既标准又高效的方式选择线程数。由于对象数量比较少,请问有什么规律可循吗?

最佳答案

只需选择一个包含hardware_concurrency 线程的线程池,并按照先到先得的原则对项目进行排队。

如果系统中的其他进程以某种方式从操作系统获得优先级,那就这样吧。这只是意味着少于分配的池大小(例如 P - 1)可以同时运行。这无关紧要,因为完成 build() 一个项目的第一个可用池线程将从队列中选择下一个项目。

要真正避免线程竞争同一核心,您可以

  • 使用信号量(如果您想实际协调来自不同进程的构建器线程,则使用进程间信号量)

  • 线程亲和性(以防止操作系统在下一个时间片将特定线程调度到不同的核心);遗憾的是,我不认为有标准、独立于平台的方式来设置线程亲和性(目前)。

我看不出有什么令人信服的理由让它变得更复杂

关于c++ - 我应该创建多少个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27973606/

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