c - 在调用 pthread_join 之前到达 pthread_exit()

标签 c linux multithreading pthreads uclibc

有这段代码:

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

void* PrintHello(void* data){

        printf("Hello from new thread\n");
        pthread_exit(NULL);

}

int main(int argc, char* argv[]){
    int rc;
    pthread_t thread_id;
    T_DATA data;

    Data = init_data();
    rc = pthread_create(&thread_id, NULL, PrintHello, (void*)data);
    if(rc){
        printf("\n ERROR: return code from pthread_create is %d \n", rc);
        exit(1);
    }
    sleep(100);
    printf("\n Created new thread (%d) ... \n", thread_id);
    pthread_join(thread_id);
}

main创建新线程然后执行 sleep(100) ,新线程可能达到pthread_exit之前 main达到pthread_join .无论如何,新线程等待并且他的资源直到main才被释放。执行 pthread_join所以如果我执行 ps命令我将在接下来的 100 秒内看到新线程,对吗?如果我使用 pthread_detach,我会得到相同的行为相反 pthread_join ?我想知道当新线程执行 pthread_exit 时会发生什么主表演前pthread_detach在线程上。

最佳答案

当然,线程在终止之前不能被清理。但在加入或分离之前也无法清除它。一个没有被分离而终止的线程将保留足够的信息以允许另一个线程加入它。

关于c - 在调用 pthread_join 之前到达 pthread_exit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20230972/

相关文章:

C 工作面试 - 类型转换和比较

C:尝试制作一个 m*n 随机正态分布数字矩阵(极坐标形式的 Box muller 2)

c - 主函数内的 sizeof(Array_Name) VS 用户定义函数内的 sizeof(Array_Name)

linux - 无法编译 .c,因为找不到 .h 文件

multithreading - 在生成访问它的子线程之前,是否应该由父线程锁定对共享资源的访问?

c++ - 如何在 C++ 中使用 future 和 promise 从函数线程获取返回值

Java ExecutorService REST 调用错误

C 递归函数调用概念

linux - 刷新页面时出现数据库被锁定的错误

linux - ldd 是否报告库的所有依赖项?