0

I am writing a multi-platform software. And I want to make configurable value number_of_cores_to_use that will be number from 1 to 4. 1- program will use 1 core,2-2 cores etc.

How can I do that with c++. Some function with option to run thread on specified core?

Bogdan Wood
  • 61
  • 1
  • 11
  • I'm a bit confused what you mean; as in an internal variable that tells your program how many threads it can spawn? Or a variable that somehow restricts your process to n-cores? – Thomas Russell Jul 06 '17 at 07:52
  • AFAIK nothing in the standard library. You probably need to specify an OS – Passer By Jul 06 '17 at 07:52
  • 1
    only related to the OS you use. Win-API, posix, ... Nothing related to c++ directly – Klaus Jul 06 '17 at 07:53
  • Possible duplicate: https://stackoverflow.com/q/150355/1025391 ? – moooeeeep Jul 06 '17 at 07:57
  • Why do you even want to do that? The OS is usually fully capable of making such decisions on its own, which usually results in much better performance than forcing threads to fixed CPU cores. If you really feel this is necessary, I would strongly recommend not adding this as a feature to the application but rather use the appropriate OS tools to do that. Otherwise, just make your application to launch only so many threads as it is supposed to use cores. One thread will always use one core. – Martin Hierholzer Jul 06 '17 at 07:58
  • 1
    Do you mean something like: 'export OMP_NUM_THREADS=4' (Linux terminal), or from inside the code 'omp_set_num_threads(maxThreads);' ? (These examples are for OpenMP). With these examples you can specify the number of cores that your application will use. – Anoroah Jul 06 '17 at 07:59
  • @MartinHierholzer It's useful when you don't want an application to hog all your cores – Passer By Jul 06 '17 at 08:07
  • You can't. The OS decides that for your. The closest you can get to that in Windows is by utilizing the [SetThreadAffinityMask](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686247(v=vs.85).aspx) function. – Ron Jul 06 '17 at 08:08
  • As for Linux this might be useful: https://linux.die.net/man/2/sched_setaffinity – moooeeeep Jul 06 '17 at 08:08
  • @passer-by The question is: why at all, and why from inside the application? Better lower the application's priority, if you want to improve the performance of other applications. – Martin Hierholzer Jul 07 '17 at 08:43

0 Answers0