2
votes

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.

6

6 Answers

4
votes

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.)

3
votes

Yes


It depends on the language, the library, and the operating system, and whether the threaded application ever actually has multiple runnable threads at the same point in time, but usually the answer is "yes".

1
votes

You can never be sure of that fact, but if it is processor-intensive (such as a game) then most likely yes.

1
votes

In that case you need to synchronized your every core of processor with memory by using volatile keyword which ensure that every core of processor getting new updated value from memory.

0
votes

Somnetimes the threads will run concurrently, sometimes not. Its all up to the package you use and the operating system and how CPU intensive each thread each.

-1
votes

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.