Consider the next piece of code :
#include <iostream>
#include <pthread.h>
#include <string.h>
using namespace std;
pthread_t tid[3];
void* printMe(void* arg)
{
pthread_t id = pthread_self();
if(pthread_equal(id,tid[0]))
{
cout << "first thread's in function" << endl;
}
if(pthread_equal(id,tid[1]))
{
cout << "second thread's in function" << endl;
}
if(pthread_equal(id,tid[2]))
{
cout << "third thread's in function" << endl;
}
}
int main() {
int i = 0;
int err;
while (i < 3)
{
err = pthread_create(&(tid[i]), NULL, printMe, NULL);
if (err != 0)
{
cout << "failed to create thread number " << i << strerror(i) << endl;
}
else
{
cout << "main() : creating thread number " << i << endl;
}
i++;
}
return 0;
}
I don't understand when does a thread invoke his function? Is that right as it's created? (while, simultaneously, the main thread keeps on creating the other threads?)
Moreover, i don't understand the output -
main() : creating thread number 0
main() : creating thread number 1
main() : creating thread number 2
first thread's in function
first thread's in function
First thread invoked his function twice while none of the other threads invoked theirs.
Then, i compiled again and got -
main() : creating thread number 0
first thread's in function
main() : creating thread number 1
second thread's in function
main() : creating thread number 2
Once again, what about the third thread?
Why "sometimes" threads don't get to invoke their functions?