Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I run several threads that match the number of CPU core/threads, will each thread run on a separate core/thread?

The threads are launched by std::async(func).

If not, how can I do it?

like image 892
Stark Avatar asked Dec 24 '22 03:12

Stark


2 Answers

The standard does not guarantee anything about on what cores/hyperthreads your threads will run. That is up to the operating system.

If you want to get platform specific (non-portable) then there are various API's to control thread affinity - like (for example) pthread_setaffinity_np on Linux. But I'd personally advice just leaving it to the OS - it will most likely do a good job unless you have very specific needs.

like image 176
Jesper Juhl Avatar answered Feb 15 '23 23:02

Jesper Juhl


In complement to Jesper's answer, the standard offers you the function std::thread::hardware_concurrency to get the number of hardware thread contexts (0 if information not available).

The way the threads are schedules is implementation dependent. You can however be sure that your code has to share the cores with dozen of OS processes/services/daemons running with their own threads.

In view of your question, as you mention std::async(func), it's worth to mention that you could force a launch policy, for example launch::async. Some implementations offer finer control, but again, the scheduling is implementation dependent.

like image 25
Christophe Avatar answered Feb 15 '23 22:02

Christophe