pthread_detach不会改变任何东西

时间:2018-03-12 18:40:05

标签: c multithreading pthreads detach pthread-join

我理解pthread_detach(pid):“当线程终止时,可以回收线程线程的存储”(根据Capitalize) 但是,我理解这意味着一旦pid线程完成执行,它的内存将被释放,我们将无法再次运行它,或者调用它的连接。 但是,我尝试了以下代码:

pthread_create(&tid, NULL, myFunction, NULL);
pthread_join(tid, NULL);

}

我得到以下内容: http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_detach.html

如果我理解正确,因为我做了pthread_detach(tid),我应该无法做到

use Mojolicious;

my $m = Mojolicious->new->log(Mojo::Log->new);
my $r = $m->renderer;

push @{$r->paths}, './templates';

my $c = Mojolicious::Controller->new->app($m);

my ($output, $format) = $r->render($c, { template => 'index' });
print $output
之后,我做了,它完美无缺。那么,如果我们仍然可以运行线程并加入它,那么做othread_detach(pid)的真正目的是什么?

非常感谢!

3 个答案:

答案 0 :(得分:0)

pthread_detach只是告诉您的程序tid的当前实例不会再次加入(pthread_join),并释放任何pthread句柄& tid实例上的对象。

如果您尝试pthread_detach该线程,则会调用pthread_join,因为它已被释放并处理掉。

我在分离调用后立即将pthread_join添加到您的代码中,您可以看到没有按预期发生任何事情。

#include <stdio.h>
#include <pthread.h>

void * myFunction (void *arg)
{
  printf ("Hello World from thread!\n");

}

int main ()
{
  pthread_t tid;
  pthread_create (&tid, NULL, myFunction, NULL);
  //pthread_join(tid, NULL);

  int isDetached = -10;
  isDetached = pthread_detach (tid);
  printf ("Is my thread detached: %d\n", isDetached);

  /* ADDED FOR STACK OVERFLOW */
  pthread_join (tid, NULL);

  int i;
  for (i = 0; i < 15; i++)
    printf ("%d\n", i);

  pthread_create (&tid, NULL, myFunction, NULL);
  pthread_join (tid, NULL);

  for (i = 0; i < 15; i++)
    printf ("%d\n", i);

  return 0;
}

我不确定会出现什么样的困惑,但如果你第二次打电话给pthread_create时,你会期待一种不同的行为;请注意,这实际上是为您创建tid的新实例。因此,您的第二个连接调用将运行该线程。

答案 1 :(得分:0)

pthread_t tid;
pthread_create(&tid, NULL, myFunction, NULL);

这会创建一个新线程,并且后续调用pthread_detach(pid)会分离创建的线程。现在

pthread_create(&tid, NULL, myFunction, NULL);

这会创建一个新线程,然后你调用了一个连接,它基本上等待新创建的线程的完成,而不是已经分离的线程。

您可以查看下面附带的代码。当您运行此代码时,即使在调用join之后,已分离的线程也会打印,即myfunc1仍在pthread_join之后打印。

#include <stdio.h>
#include <pthread.h>

void *myFunction2 (void *arg)
{
    printf("Hello World from func2!\n");

}

void *myFunction1 (void *arg) 
{
    while(1) {
        printf("Hello World from func1\n");
    }
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, NULL, myFunction1, NULL);
    //pthread_join(tid, NULL);

    int isDetached = -10;
    isDetached = pthread_detach(tid);
    printf("Is my thread detached: %d\n", isDetached);

    int i;

    pthread_create(&tid, NULL, myFunction2, NULL);
    pthread_join(tid, NULL);

    for (i = 0; i<15; i++)
        printf("%d\n", i);

    return 0;
}

答案 2 :(得分:0)

您的变量tid 一个帖子。你的程序没有启动一个线程两次,它会创建两个完全不同的线程。

实际线程是操作系统中存在的对象。您的tid变量只是一个&#34;句柄&#34;您可以用来与线程进行交互。您对pthread_create(&tid,...)的第二次调用是重新使用handle变量,将其指向一个新的不同线程。

相关问题