简体   繁体   中英

Why do these threads not execute in the same order as the code?

I'm new to threading in C and was messing around in an attempt to learn about it. I compiled and executed the (very basic) code below:

void *thread(void *vargp);

int main(int argc, char **argv) {
  pthread_t tid1, tid2;

  printf("Hello from the main thread.\n");

  printf("Creating thread 1.\n");
  pthread_create(&tid1, NULL, thread, NULL); 
  printf("Creating thread 2.\n");
  pthread_create(&tid2, NULL, thread, NULL);

  printf("Main thread is going to wait on peer threads.\n");
  pthread_join(tid1, NULL);
  pthread_join(tid2, NULL);
  printf("Peer threads have completed.\n");

  return EXIT_SUCCESS;
}

void *thread(void *vargp) {
  pthread_t tid = pthread_self();
  printf("Hello from thread %u.\n", (unsigned int)tid);
  return NULL;
}

I expected the output to be...

Hello from the main thread.
Creating thread 1.
Hello from thread [number].
Creating thread 2.
Hello from thread [number].
...

But instead, it was:

Hello from the main thread.
Creating thread 1.
Creating thread 2.
Main thread is going to wait on peer threads.
Hello from thread 3067947840.
Hello from thread 3076340544.
...

Why was the output in this order? Did the two threads wait until the join function to execute or did they just happen to take that long? Do threads need to be joined to the main thread in order to print output to the console?

Thanks for explaining this to me!!

You have only created threads 1 and 2 in order. But they'are necessarily executed in that order. The execution order is depends on how they're scheduled, number of processors available, etc. So you could see the output from the two threads in any order.

If you would like to the output in "order", you could wait for first thread to complete before starting the next one.

  printf("Creating thread 1.\n");
  pthread_create(&tid1, NULL, thread, NULL); 
  pthread_join(tid1, NULL);
  printf("Creating thread 2.\n");
  pthread_create(&tid2, NULL, thread, NULL);
  pthread_join(tid2, NULL);

This, of course, defeats the purpose of mutli-threading as only one thread ever does anything useful.

The ordering can be achieved in many ways. A simple way could be to use a semaphore .

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