I was watching this tutorial and following is the code. The line "Beauty is only skin deep" gets printed at different position of number i, why does this happen?
PS , I am new to threading.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream>
#include<thread>
usingnamespace std;
void function_1(){
cout<<"Beauty is only skin deep"<<endl;
}
int main()
{
thread t1(function_1); //t1 is running.
for(int i=0;i<100;i++)
{
cout<<"from main : "<<i<<endl;
}
t1.join();
return 0;
}
Your computer has many running processes. The OS decides when and how much each of them gets CPU-time. Your two threads are among them. In other words there are more than just your code that affects how your binary executes.
Threads are asynchronous. Not sychronous. They execute independently. We only know the earliest point where the t1 can start executing (line 11) and that the main thread waits on line 16 until t1 has completed.