Reputation: 11
I wonder if it is possible for a single-threaded program to run on multiple cores?
public static void main(String[] args){
int var1 = x + y;
int var2 = var1 + 1;
System.out.println(var1 + var2);
}
Just as an example, in the above code since var2
depends on var1
so I assume those two lines can't run on different cores because we don't know what would be the order of execution. However, if they don't depend on each other then is it possible that we can run them in parallel? I thought it might be more efficient for some heavy computation problems. Appreciate any feedback.
Upvotes: 1
Views: 285
Reputation: 27190
I assume those two lines can't run on different cores.
You should not trust that assumption. Here is what you can safely assume: You can assume that if a single thread calls main()
, then the outcome will be the same as if the statements were executed in program order (I.e., the order in which they appear in the source code.)
The theoretical reason why you should not assume anything about the number of cores is that, whatever language you are talking about, the language specification probably does not say anything about "cores." In some far-out scenario—maybe it will never happen, but who knows?—some highly-advanced build-tool/OS/hardware system could conceivably split up the execution of a single large function by a single thread across multiple "cores." So long as it obeys the guarantee that the outcome will be the same AS IF it all was done sequentially by a single core, then everybody should be happy.
The practical reason why you should not trust your assumption about the number of cores is, while a thread is executing main, it could be preempted at any time by the OS scheduler, and if your program has not requested any affinity of its threads for particular cores, then when the scheduler eventually resumes the thread, it could be resumed on any available core.
Upvotes: 2