【问题标题】:How to wait two pthreads?如何等待两个 pthread?
【发布时间】:2015-01-11 05:38:35
【问题描述】:

谁能告诉我最后两行代码之间发生了什么

// Creating Server and Client threads
pthread_create(&serverThread, NULL, (void* (*)(void*))&Server,(void *)0);

pthread_create(&clientThread, NULL, (void* (*)(void*))&Client,(void *)1);

// Wait until serverThread exits
pthread_join( serverThread, NULL);

// Wait until clientThread exits
pthread_join( clientThread, NULL);

我想同时等待他们。如果两个线程之一终止/退出怎么办?如果服务器一直在无限循环中运行怎么办?

【问题讨论】:

  • 请告诉我们您的错误是什么。
  • 我不是在谈论错误:) 我的问题是:最后两行代码之间会发生什么?
  • 看这里yolinux.com/TUTORIALS/…。请先编译您的代码。
  • 如果小行星在第一次和第二次调用pthread_join 之间撞击地球怎么办?请说明您希望通过同时等待来避免什么样的款待。一个线程可以终止,这是大多数线程所做的,pthread_join 让您完全等待。另一个不清楚。同时等待如何让你从无限循环中恢复?

标签: c++ pthreads pthread-join


【解决方案1】:

第一个连接 - pthread_join(serverThread, NULL); 将等到 serverThread 终止。

clientThread 可能会或可能不会在此期间终止;如果它终止,它将保持僵尸状态,直到调用pthread_join(clientThread, NULL);pthread_join 在这种情况下会立即返回。

如果调用pthread_join(clientThread, NULL);clientThread还没有完成执行,它会再次等待直到clientThread终止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    相关资源
    最近更新 更多