Reputation: 125
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.
Upvotes: 0
Views: 255
Reputation: 76489
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.
Upvotes: 1
Reputation: 8945
As this program executed, the order of events was this:
If you ran this program many times, then eventually you just might encounter a case where the child "beat its parent to the punch." (But this also has to do with the underlying operating-system logic which ensures that outputs to the console always consist of "entire strings." Either of the two processes/threads had an equal chance to get their strings in first, but you'll never see console output consisting of the two strings intermingled.)
The ordering of statements in the source code is entirely irrelevant.
Upvotes: 2