gpt4 book ai didi

linux - 如何让多线程应用程序在 VMWare 下使用 Ubuntu 上的所有内核?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:40:15 27 4
gpt4 key购买 nike

我有一个处理非常大的数据文件的多线程应用程序。在 Window 7 上运行良好,代码全部为 C++,使用 pthreads 库进行跨平台多线程处理。当我在我的 Intel i3 上的 Windows 下运行它时 - 任务管理器显示所有四个内核都已达到极限,这正是我想要的。使用 g++ Ubuntu/VMWare 工作站编译了相同的代码 - 启动了相同数量的线程,但所有线程都在一个核心上运行(据我所知 - 任务管理器只显示一个核心忙碌)。

我将深入研究 pThreads 调用 - 也许我错过了一些默认设置 - 但如果有人有任何想法,我想听听他们的意见,我可以提供更多信息 -

更新:我确实设置了 VMWare 以查看所有四个内核,而/proc/cpuinfo 显示了 4 个内核

更新 2 - 刚刚编写了一个简单的应用程序来显示问题 - 也许它只是 VMWare? - 任何 Linux 本地人都想尝试看看这是否真的会降低多个内核的负载?要在 Windows 上运行它,您需要 pThread 库 - 可轻松下载。如果有人能提出比 printf 更占用 CPU 资源的建议,请继续!

#ifdef _WIN32
#include "stdafx.h"
#endif
#include "stdio.h"
#include "stdlib.h"
#include "pthread.h"

void *Process(void *data)
{
long id = (long)data;
for (int i=0;i<100000;i++)
{
printf("Process %ld says Hello World\n",id);
}
return NULL;
}

#ifdef _WIN32
int _tmain(int argc, _TCHAR* argv[])
#else
int main(int argc, char* argv[])
#endif
{
int numCores = 1;
if (argc>1)
numCores = strtol(&argv[1][2],NULL,10);
pthread_t *thread_ids = (pthread_t *)malloc(numCores*sizeof(pthread_t));
for (int i=0;i<numCores;i++)
{
pthread_create(&thread_ids[i],NULL,Process,(void *)i);
}
for (int i=0;i<numCores;i++)
{
pthread_join(thread_ids[i],NULL);
}
return 0;
}

最佳答案

我稍微修改了你的代码。我将 numCores = strtol(&argv[1][2], NULL, 10); 更改为 numCores = strtol(&argv[1][0], NULL, 10); 通过调用 ./core 4 使其在 Linux 下工作,也许你在核心数前面传递了一些东西,或者因为类型 _TCHAR 是每个字符 3 个字节?对 Windows 不太熟悉。此外,由于我无法仅使用 printf 对 CPU 施加压力,我还稍微更改了 Process。

void *Process(void *data)
{
long hdata = (long)data;
long id = (long)data;
for (int i=0;i<10000000;i++)
{
printf("Process %ld says Hello World\n",id);
for (int j = 0; j < 100000; j++)
{
hdata *= j;
hdata *= j;
hdata *= j;
hdata *= j;
hdata *= j;
hdata *= j;
hdata *= j;
hdata *= j;
hdata *= j;
hdata *= j;
hdata *= j;
...
}
}

return (void*)hdata;
}

现在当我运行 gcc -O2 -lpthread -std=gnu99 core.c -o core && ./core 4 你可以看到所有 4 个线程都在 4 个不同的内核上运行它们一次从一个核心交换到另一个核心,但所有 4 个核心都在超时工作。

core.c: In function ‘main’:
core.c:75:50: warning: cast to pointer from integer of different size [-Wint-to-pointer- cast]
Starting 4 threads
Process 0 says Hello World
Process 1 says Hello World
Process 3 says Hello World
Process 2 says Hello World

我用 htop 验证了它,希望它有帮助。:) 如果你想知道的话,我运行专用的 Debian SID x86_64 和 4 核。

关于linux - 如何让多线程应用程序在 VMWare 下使用 Ubuntu 上的所有内核?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6488432/

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