I'm studying about threads and slightly confused about 1 thing.
If I have a single process with multiple threads running on a dual/quad core CPU, will different threads run concurrently on different cores?
Thanks in advance.
It Depends.
At least on Linux, each task gets assigned to a set of CPUs that it can execute on (processor affinity
). And, at least on Linux, the scheduler will try to schedule the task on the same processor as last time, so that it gets the best benefit of CPU cache re-use. The hilarious thing is that it doesn't always rebalance when the system is under load, so it is possible to run one core quite hot and contested and leave three cores cool and relatively idle. (I've seen this exact behavior with the Folding @ Home client.)
You can force the affinity you need with the pthread_setaffinity_np(3)
routine for threaded applications or sched_setaffinity(2)
for more traditional Unix-style fork(2)
ed applications. Or you can use the taskset(1)
program to set the affinity before or after starting an application. (Which is the approach I took with my silly Folding @ Home client -- it was easy to modify the initscript to call taskset(1)
to set the affinity of each client process correctly, so each client got its own core and didn't compete for resources with the other clients on different sibling HyperThreaded 'faked' execution cores.)
I think that you are loosing the idea behind concurrency; it's not that you are looking to run processes on multiple cores. Instead, you're needing to not block on one process the entire time. A perfect example of this is with threading network listeners. You want to perform an accept which will actually create a new client->server socket. After this you want to do some processing with that socket while still be able to take new connections. This is where you would want to generate a thread to perform the processing so that the accept can get back on track to waiting for a new connection.