如何使多线程应用程序使用VMWare下的Ubuntu上的所有核心?

时间:2011-06-27 03:51:59

标签: linux multithreading ubuntu vmware

我有一个处理非常大的数据文件的多线程应用程序。在Window 7上运行良好,代码全部是C ++,使用pthreads库进行跨平台多线程。当我在英特尔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;
}

1 个答案:

答案 0 :(得分:0)

我改变了你的代码。我将numCores = strtol(&argv[1][2], NULL, 10);更改为numCores = strtol(&argv[1][0], NULL, 10);以使其在Linux下工作,方法是调用./core 4,也许你在核心数量前传递内容,或者因为每个字符的类型_TCHAR是3byte?不熟悉windows ..更进一步,因为我不能仅用printf来强调CPU,我也改变了一点处理。

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个字符,以防你想知道。

相关问题