4

I want my software to create one thread per core, obviously different Macs have a different number of cores.

Does anyone know how to (programmatically, via Cocoa) determine the number of cores?

JWWalker
  • 22,385
  • 6
  • 55
  • 76
Geesu
  • 5,928
  • 11
  • 43
  • 72
  • 3
    You may want to look into Grand Central Dispatch, which manages the number of threads for you and simplifies a great many other things as well. – Peter Hosey Nov 16 '11 at 19:47
  • Related: [How do I detect a dual core CPU on iOS?](http://stackoverflow.com/questions/7241936/how-do-i-detect-a-dual-core-cpu-on-ios) (but it's not a dupe, my bad) – bobobobo Aug 14 '13 at 18:02

2 Answers2

26
[[NSProcessInfo processInfo] processorCount]
JWWalker
  • 22,385
  • 6
  • 55
  • 76
  • This is a "Cocoa" answer, but it only provides the number of logical cores, not the number of physical cores. Unclear which the asker actually wants. – bhaller Jul 05 '19 at 13:32
2

See How do I detect a dual core CPU on iOS? It works in OS X too.

unsigned int countCores()
{
    size_t len;
    unsigned int ncpu;
    len = sizeof(ncpu);
    sysctlbyname ("hw.ncpu",&ncpu,&len,NULL,0);
    return ncpu;
}
Community
  • 1
  • 1
Jano
  • 62,815
  • 21
  • 164
  • 192
  • This answer is more flexible, although less "Cocoa", because sysctlbyname() can provide information on the number of physical cores as well as the number of logical cores, etc. (see its man page). – bhaller Jul 05 '19 at 13:33