c - pthread_detach 不会改变任何东西

标签 c multithreading pthreads detach pthread-join

我理解 pthread_detach(pid) :“当该线程终止时可以回收该线程的存储”(根据 http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_detach.html ) 但是,我理解这意味着一旦 pid 线程完成执行,其内存将被释放,我们将无法再次运行它,或对其调用 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);

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;

}

我得到以下信息: result

如果我理解正确的话,既然我做了 pthread_detach(tid),我应该做不到

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

之后,我还是这么做了,而且效果很好。那么,如果我们仍然可以运行线程并加入它,那么执行 othread_detach(pid) 的真正目的是什么?

非常感谢!

最佳答案

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 实例。因此,您的第二个 join 调用将运行该线程。

关于c - pthread_detach 不会改变任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49242346/

相关文章:

取消或杀死 pthread

c++ - Openssl DSA 标志

ios - AFHTTPClient + enqueueBatchOfHTTPRequestOperations : handle cancellation and errors

c - 如果你必须在 if 语句中放置 break,为什么我们需要在 while 操作中为条件操心?

python - “模块”对象没有属性 '_strptime',有多个线程 Python

multithreading - 不同线程上的 Quarkus 事务

multithreading - gcc参数: -pthread.它是做什么的?

C/POSIX- pthread_t 阻塞直到任务完成

c - 输出中存在字符的说明

c - 预生成的公共(public)/私有(private) RSA key ,无法在 C 中解密(在 python 中工作)