简体   繁体   中英

Creating threads (POSIX threads)

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.

As this program executed, the order of events was this:

  • The main program executed.
  • It launched the child thread.
  • Coincidentally(!) it managed to print its message before...
  • ... the newly-launched child thread printed its message.
  • Then the child thread died, and...
  • ... having waited for it to die... the main thread did too.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM