I'm trying to know why does the Master executes the printf()
first even though the Slave thread comes first in the code?
Also, why do they have the same PIDs (Master and slave)?
void* pthread_function(int id) {
printf("[%s] Slave thread %d (PID=%d,TID=%ld)\n",timestamp(),id,getpid(),pthread_self());
pthread_exit(NULL);
}
int main(int argc,char** argv) {
// Create slave thread
long int i = 1;
pthread_t thread;
pthread_create(&thread,NULL,(void* (*)(void*))pthread_function,(void*)(i));
// Print message
printf("[%s] Master thread (PID=%d,TID=%ld)\n",timestamp(),getpid(),pthread_self());
// Wait for threads
pthread_join(thread,NULL);
// Terminate process OK
return 0;
}
and the output was
[2019:11:20 00:25:25:853640] Master thread (PID=5338,TID=140000137201472)
[2019:11:20 00:25:25:853795] Slave thread 1 (PID=5338,TID=140000128689920)
Sorry I'm new to this, the answer might be very simple and i don't know it.
Multiple threads are scheduled independently, so the kernel may decide to schedule the new thread or the old one first, depending on its priority and what else is running on the system. Running the program multiple times may result in different results, even.
The reason that the two threads share the same PID is because POSIX says they must. There is one process, even with multiple threads. The kernel internally tracks the two threads with separate PIDs, but glibc exposes a single PID (the PID of the main thread) as the PID of the process.