Reputation: 1176
I am beginner in multithreaded programming so at present I don't clearly know what is happening into the background. Please help me to understand the following scenario-
I've just tested a simple multithreading program using C++ 11. I compiled and ran the code using g++ -std=c++11 -pthread thread.cpp -o thread && ./thread
command into my ubuntu terminal.
I ran the code several times by keeping the code same. Though I used ++i
instead of i++
, I think it doesn't matter. The thing is, I observed different kind of output for the same code. As I am passing the argument sequentially by 0-9, I expected a sequential result in the output. But it was different every time I ran the code. Why? What is actually happening in the background?
Here is the code and output of my program:
Upvotes: 0
Views: 715
Reputation: 20396
Parallel execution is non-deterministic. The various reasons and rationales for why this is are massive in scope and variety, but the basic gist of it is that Threading is controlled by the underlying Operating System, and the OS can have many priorities/assumptions about when threads need to run and when they don't, and very few of those variables are exposed to the user.
If it is absolutely necessary to have one item run before another item, you need to run in serial, or otherwise have some smarter programming paradigms put in place.
Upvotes: 2
Reputation: 3379
Because you really can't predict when the thread scheduler will schedule which thread. It just schedules them.
Although you can force to work on a specific thread by calling join
on that thread.
The sense of thread is exactly this.
Upvotes: 1
Reputation: 182753
It would be an astonishing coincidence if the most efficient order to do the work happened to precisely match the order in which you requested that the work be done.
For example, consider a system with four cores. The code that creates the jobs is running on one core. So we might expect the first three jobs to get their own cores fairly immediately. Then the next seven jobs have to wait for available cores. But once we create the last thread, it makes the most sense to run the last job, since that thread is hot in the cache. So why wouldn't the scheduler run that last job?
Of course, this is all based on guesses about what resources might be available and what might happen. Why would you have any expectations about that?
Upvotes: 2