利用 c++/c 中的全部 4 个核心

发布于 2024-12-12 05:46:30 字数 148 浏览 0 评论 0 原文

我有一个将创建 4 个线程的主进程。如果我只是运行所有 4 个线程,内核会利用所有 4 个内核,还是程序会在单个内核上进行多线程?如果不是,那么如何在多核上处理同步。我有一个 4 核英特尔 cpu,我的程序是用 c++ 编写的,

我在虚拟机的 Linux 上运行它。

I have a main processes that will create 4 threads. If i simply run all 4 threads would the kernel utilize all 4 cores or will the program be multithreaded on a single core? if not then how would synchronization be handled on a multicore. I have a 4core intel cpu and my program is in c++

Im running this on a linux in a Virtual machine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

方圜几里 2024-12-19 05:46:30

你真的不知道。

一方面,C++03 标准对线程、内核或任何此类内容一无所知。所以无论如何,这都是依赖于平台的。

但即使从平台的角度来看,您通常仍然不知道。操作系统调度线程和作业。操作系统可能(也可能不会)为您提供指定“处理器亲和力”,但这通常需要一些跳跃才能利用。

您还应该记住的一件事是,如果您的目标是保持每个核心 100% 利用率,您通常需要超过 n 个线程(其中 n是核心数)。线程花费大量时间休眠、等待磁盘,并且通常不在核心上执行任何操作。您需要的确切线程数取决于您的实际应用程序和平台,但实验可以帮助指导您对此进行微调。

You don't really know.

For one thing, the C++03 Standard doesn't know anything about threads, cores or any of that kind of stuff. So this is all platform-dependant anyway.

But even from a platform point-of-view, you often still don't really know. The operating system schedules threads and jobs. The OS might -- or might not -- give you the means to specify a "processor affinity" for a particular thread, but this typically takes some hoop-jumping-through to utilize.

One of the things you also should keep in mind is that if your goal is to keep each core 100% utilized, you'll often need more than n threads (where n is number of cores). Threads spend a lot of time sleeping, waiting on disk, and generally not doing anything on the core. The exact number of threads you'll need depends on your actual application and platform, but experimentation can help guide you towards fine tuning this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文