为什么这些线程的执行顺序与代码不一样?

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

我是 C 线程的新手,正在四处乱逛以尝试了解它。我编译并执行了下面的(非常基本的)代码:

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;
}

我预计输出是...

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

但相反,它是:

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.
...

为什么输出是这样的?这两个线程是等到 join 函数执行还是恰好花了那么长时间?是否需要将线程连接到主线程才能将输出打印到控制台?

谢谢你给我解释!!

您只按顺序创建了 个线程 1 和线程 2。但它们必须按此顺序执行。执行顺序取决于它们的调度方式、可用处理器的数量等。 因此您可以按任意顺序查看两个线程的输出。

如果您想要 "order" 中的输出,您可以等待第一个线程完成后再开始下一个线程。

  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);

这当然违背了多线程的目的,因为只有一个线程可以做任何有用的事情。

可以通过多种方式实现排序。一种简单的方法是使用 semaphore.