10

Possible Duplicate:
how to set CPU affinity of a particular pthread?

I am writing a c++ program, using g++ compiler in Ubuntu. I have 4 threads in my program and 4 cores on my CPU. I want to be sure that each thread will be run on a different core. I am rarely familiar with pthread.

Community
  • 1
  • 1
Saeed
  • 7,262
  • 14
  • 43
  • 63
  • 2
    Can I ask why you want to do this? If you ensure that the treads don't bock each other (so they can run at the same time), the OS will take care of scheduling them whenever any core has free time. – James Sep 25 '11 at 10:12
  • @autopulated, actually having core and socket affinity can affect performance greatly. imagine fork/join, normally you'd like the extra threads to be scheduled on free cores, not start on the same (as it is usually faster) in order to actually run in parallel. Also you'd prefer be scheduled on the same socket 1st for utilize locality. – bestsss Sep 25 '11 at 10:28
  • Locality is a good reason, but as pointed out by David below, the results aren't necessarily as good as you'd expect. – James Sep 25 '11 at 10:33
  • @bestsss In simple cases (i.e. one process doing all the work) the scheduler will ensure locality for you. – David Heffernan Sep 25 '11 at 10:53
  • @David, the scheduler usually spawns new threads on the same core, they work a bit and get rescheduled. Unless it was clear imagine 2 sockets w/ 4cores each. You have 2 fork/join tasks going on (in the same process), call 2 sorts. You'd like to have the threads on a single sort operation to reside on the same socket, so the communication through the caches is faster. – bestsss Sep 25 '11 at 10:58
  • lemme just add that sometimes there is a benefit to doing this. One of my projects saw a 4% increase when setting thread affinity explicitly to each core. That was on a VM (Xeon E5-2690 with 2 cores no HT). That said, doing this on the prod cluster (8 cores with HT) causes a severe drop in performance and in some cases, my dev VM was faster. – Mel Sep 16 '13 at 05:23

2 Answers2

14

Don't do this. Let the system schedule the threads. If you affinitise the threads to distinct cores you just handicap the scheduler. When your app is the only one consuming CPU, the scheduler will naturally schedule each thread on a separate core.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 13
    This is a comment, not an answer. It's probably correct, but if the idea of the exercise is to find out what happens when the threads are pinned, then you're discouraging learning. Why not burn the Linux manuals while you're at it, knowledge is dangerous ;-p – Steve Jessop Sep 25 '11 at 11:00
6

See sched_setaffinity function: http://manpages.courier-mta.org/htmlman2/sched_setaffinity.2.html

Alex F
  • 42,307
  • 41
  • 144
  • 212