【问题标题】:Why do these threads not execute in the same order as the code?为什么这些线程的执行顺序与代码不同?
【发布时间】:2020-04-13 00:56:16
【问题描述】:

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

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

感谢您向我解释这一点!

【问题讨论】:

  • pthread_create 只是创建一个新线程,但绝不会等待线程运行。实际线程何时运行取决于操作系统调度程序。如果您想在线程之间进行排序,则必须使用诸如互斥锁、信号量、屏障等同步机制显式编码。

标签: c multithreading pthreads


【解决方案1】:

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

如果您想按“顺序”输出,您可以等待第一个线程完成后再开始下一个线程。

  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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多