I wrote a small program to see the amount of overhead there is to create a thread.
Here is the program (I wrote it quickly so it isn’t the best):
#include <iostream>
#include <pthread.h>
void * lala(void * cake) {
int * hi = (int *)cake;
std::cout << *hi << '\n';
}
int main(void) {
pthread_t thread;
for (int i = 0;i < 10000;i = i + 1) {
pthread_create(&thread,0,lala,&i);
}
}
It basically launches 10000 threads and passes them their thread number, and each thread outputs its number.
The output changes each time I run the program, however I noticed that there was one part that never changed:
At the end of the output, I always find this:
...
9994
9995
9996
9997
9998
9999
0
Which means that the first thread finishes last…
So, my friends, does anyone have a possible explanation for this phenomenon?
First thing, you are passing the address-of a local variable to the thread, which is constantly changing. So, when the thread gets time to read it, the content of
iwould already be changed.Why can’t you just pass
iinstead of&i, where variable is just of 4-bytes (i.e. fits in pointer)?Secondly, you shouldn’t be concerned how OS schedules your threads.