首页 > 解决方案 > pthread_create 将终止具有相同 tid 的先前线程?

问题描述

我发现在下面的代码中,每次接受新客户端时都会创建一个线程。在函数 pthread_client() 中没有退出日志。但似乎命令没有创建多线程ps aux

我的理解是每次创建相同tid的新线程时,都会自动杀死具有相同tid的旧线程,对吗?谢谢!

while(1){
    fd = accept(...);
    pthread_create(&tid1, NULL, (void *)pthread_client, (void *)arg);
    pthread_detach(tid1);
}

标签: linuxmultithreading

解决方案


我的理解是每次创建相同tid的新线程时,都会自动杀死具有相同tid的旧线程,对吗?谢谢!

不,你错了!

从手册:

 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);

在返回之前,成功调用 pthread_create() 会将新线程的 ID 存储在 thread 指向的缓冲区中;

这意味着:tid每次调用都会在您的变量中存储一个值。旧值将被覆盖,只是它不再在代码中使用。所以你总是得到一个新线程,但你的代码以后不能访问“旧”线程。但如您所见,您的代码只是从当前新创建的线程中分离出来,因此以后无需处理任何内容。

先前创建的线程只是继续。您不能通过调用来终止正在运行的线程pthread_create


推荐阅读