【问题标题】:What happens to the pthread when it exits the functionpthread 退出函数时会发生什么
【发布时间】:2015-11-03 23:13:16
【问题描述】:

假设我在while 循环中使用pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*fun) (void *), void *arg),一旦它完成函数fun(),线程会发生什么,如果我调用int pthread_detach(pthread_t thread),它是否也会落入主线程的循环中?还是只有主线程留在循环中?

例子:

pthread_t t[NTHREADS];

int i = -1;
while(1){

  //do something
  ++i;

  pthread_create(&t[i], NULL, fun, (void *)i);
  pthread_detach(t[i]);

  //main thread goes on, created one detaches when finished

}

我想要做的是一个多客户端服务器,其中每个线程为其自己的客户端提供服务,有 NTHREADS 并且当某个线程完成 fun() 或者更确切地说为它的客户端提供服务时,t[] 中的插槽打开并如果之前已满,可以创建另一个线程(其他客户端可以连接)。

【问题讨论】:

  • 您需要一个互斥锁来保护t,以便线程可以在返回之前安全地将t[i] 设置为“未使用”值。

标签: c multithreading pthreads


【解决方案1】:

规范说从线程函数返回等效于调用pthread_exit,线程函数的返回值对pthread_join 可用(前提是您没有分离线程)。

通常,这是通过让pthread_create 创建一个开始执行固定(libc)“线程入口函数”的线程来实现的。此入口函数调用您的函数,然后调用pthread_exit(在完成任何相关清理之后)。

【讨论】:

    【解决方案2】:

    从其 start 函数返回的 pthread 等效于调用 pthread_exit 的那个线程。如果线程被分离,它就不复存在了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-25
      • 2015-07-10
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 2011-10-04
      • 2017-06-12
      • 2018-02-05
      相关资源
      最近更新 更多